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/test-and-deploy.yml b/.github/workflows/test-and-deploy.yml index 9bba6d8bac..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.7', '3.8', '3.9', '3.10', '3.11' ] + python-version: [ '3.8', '3.9', '3.10', '3.11', '3.12', '3.13' ] steps: - name: Checkout twilio-python uses: actions/checkout@v3 @@ -33,6 +33,7 @@ jobs: run: | pip install virtualenv --upgrade make install test-install + make prettier - name: Run the tests run: make test-with-coverage @@ -46,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 bd1ce355ca..5ac12d5bb4 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,6 +3,1593 @@ twilio-python Changelog Here you can see the full list of changes between each twilio-python release. +[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** +- Adds validity period Default value in service resource documentation + + +[2025-01-09] Version 9.4.2 +-------------------------- +**Library - Chore** +- [PR #832](https://github.com/twilio/twilio-python/pull/832): remove test for 3.7. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Numbers** +- Change beta feature flag to use v2/BulkHostedNumberOrders + + +[2024-12-13] Version 9.4.1 +-------------------------- +**Library - Fix** +- [PR #827](https://github.com/twilio/twilio-python/pull/827): Fixing init file for preview iam domain. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + +**Library - Chore** +- [PR #826](https://github.com/twilio/twilio-python/pull/826): fix orgs api changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + + +[2024-12-12] Version 9.4.0 +-------------------------- +**Library - Feature** +- [PR #825](https://github.com/twilio/twilio-python/pull/825): Docs update and examples for organization api uptake and public oauth. Thanks to [@AsabuHere](https://github.com/AsabuHere)! +- [PR #815](https://github.com/twilio/twilio-python/pull/815): Organizations Api uptake for twilio-python. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + + +[2024-12-05] Version 9.3.8 +-------------------------- +**Api** +- Add optional parameter `intelligence_service` to `transcription` +- Updated `phone_number_sid` to be populated for sip trunking terminating calls. + +**Numbers** +- Add Update Hosted Number Order V2 API endpoint +- Update Port in docs + +**Twiml** +- Add optional parameter `intelligence_service` to `` +- Add support for new `` and `` noun +- Add `events` attribute to `` verb + + +[2024-11-15] Version 9.3.7 +-------------------------- +**Library - Chore** +- [PR #819](https://github.com/twilio/twilio-python/pull/819): use older verison of aiohttp_retry. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- Added `ivr-virtual-agent-custom-voices` and `ivr-virtual-agent-genai` to `usage_record` API. +- Add open-api file tag to realtime_transcriptions + +**Taskrouter** +- Add `api-tag` property to workers reservation +- Add `api-tag` property to task reservation + + +[2024-10-25] Version 9.3.6 +-------------------------- +**Library - Chore** +- [PR #818](https://github.com/twilio/twilio-python/pull/818): removing unavailable references from init files. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + + +[2024-10-24] Version 9.3.5 +-------------------------- +**Conversations** +- Expose ConversationWithParticipants resource that allows creating a conversation with participants + + +[2024-10-17] Version 9.3.4 +-------------------------- +**Api** +- Add response key `country` to fetch AvailablePhoneNumber resource by specific country. + +**Messaging** +- Make library and doc public for requestManagedCert Endpoint + + +[2024-10-03] Version 9.3.3 +-------------------------- +**Library - Chore** +- [PR #816](https://github.com/twilio/twilio-python/pull/816): add assistants init files. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Messaging** +- Add A2P external campaign CnpMigration flag + +**Numbers** +- Add address sid to portability API + +**Verify** +- Add `SnaClientToken` optional parameter on Verification check. +- Add `EnableSnaClientToken` optional parameter for Verification creation. + + +[2024-09-25] Version 9.3.2 +-------------------------- +**Accounts** +- Update docs and mounts. +- Change library visibility to public +- Enable consent and contact bulk upsert APIs in prod. + +**Serverless** +- Add is_plugin parameter in deployments api to check if it is plugins deployment + + +[2024-09-18] Version 9.3.1 +-------------------------- +**Library - Chore** +- [PR #813](https://github.com/twilio/twilio-python/pull/813): add static init file to iam domain. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Intelligence** +- Remove public from operator_type +- Update operator_type to include general-availablity and deprecated + +**Numbers** +- Remove beta flag for bundle clone API + + +[2024-09-05] Version 9.3.0 +-------------------------- +**Iam** +- updated library_visibility public for new public apikeys + +**Numbers** +- Add new field in Error Codes for Regulatory Compliance. +- Change typing of Port In Request date_created field to date_time instead of date **(breaking change)** + + +[2024-08-26] Version 9.2.4 +-------------------------- +**Library - Chore** +- [PR #810](https://github.com/twilio/twilio-python/pull/810): add license identifier to project metadata. Thanks to [@mschoettle](https://github.com/mschoettle)! +- [PR #808](https://github.com/twilio/twilio-python/pull/808): preview iam removal. Thanks to [@manisha1997](https://github.com/manisha1997)! +- [PR #807](https://github.com/twilio/twilio-python/pull/807): update intersphinx_mapping. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #804](https://github.com/twilio/twilio-python/pull/804): add init file. Thanks to [@manisha1997](https://github.com/manisha1997)! + +**Api** +- Update documentation of `error_code` and `error_message` on the Message resource. +- Remove generic parameters from `transcription` resource +- Added public documentation for Payload Data retrieval API + +**Flex** +- Adding update Flex User api + +**Insights** +- Added 'branded', 'business_profile' and 'voice_integrity' fields in List Call Summary + +**Intelligence** +- Add `words` array information to the Sentences v2 entity. +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` headers for Operator Results. +- Change the path parameter when fetching an `/OperatorType/{}` from `sid` to `string` to support searching by SID or by name +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` headers for Transcript and Service endpoints. + +**Messaging** +- Adds two new channel senders api to add/remove channel senders to/from a messaging service +- Extend ERC api to accept an optional attribute in request body to indicate CNP migration for an ERC + +**Numbers** +- Modify visibility to public in bundle clone API +- Add `port_date` field to Port In Request and Port In Phone Numbers Fetch APIs +- Change properties docs for port in phone numbers api +- Add is_test body param to the Bundle Create API +- Change properties docs for port in api + +**Trusthub** +- Add new field in themeSetId in compliance_inquiry. + +**Verify** +- Update `custom_code_enabled` description on verification docs + + +[2024-07-02] Version 9.2.3 +-------------------------- +**Intelligence** +- Deprecate account flag api.twilio-intelligence.v2 + + +[2024-06-27] Version 9.2.2 +-------------------------- +**Api** +- Add `transcription` resource + +**Flex** +- Changed mount name for flex_team v2 api + +**Intelligence** +- Add `X-Rate-Limit-Limit`, `X-Rate-Limit-Remaining`, and `X-Rate-Limit-Config` as Response Headers to Operator resources + +**Numbers** +- Added include_constraints query parameter to the Regulations API + +**Twiml** +- Add support for `` noun + + +[2024-06-21] Version 9.2.1 +-------------------------- +**Api** +- Add beta feature request managed cert + + +[2024-06-18] Version 9.2.0 +-------------------------- +**Library - Chore** +- [PR #796](https://github.com/twilio/twilio-python/pull/796): adding contentType in post and put. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Events** +- Add `status` and `documentation_url` to Event Types + +**Lookups** +- Removed unused `fraud` lookups in V1 only to facilitate rest proxy migration + +**Numbers** +- Add date_created field to the Get Port In Request API +- Rename the `status_last_time_updated_timestamp` field to `last_updated` in the Get Port In Phone Number API **(breaking change)** +- Add Rejection reason and rejection reason code to the Get Port In Phone Number API +- Remove the carrier information from the Portability API + +**Proxy** +- Change property `type` from enum to ienum + +**Trusthub** +- Add skipMessagingUseCase field in compliance_tollfree_inquiry. + + +[2024-06-06] Version 9.1.1 +-------------------------- +**Api** +- Mark MaxPrice as obsolete + +**Lookups** +- Update examples for `phone_number_quality_score` + +**Messaging** +- List tollfree verifications on parent account and all sub-accounts + + +[2024-05-24] Version 9.1.0 +-------------------------- +**Library - Chore** +- [PR #789](https://github.com/twilio/twilio-python/pull/789): [Snyk] Security upgrade aiohttp from 3.8.6 to 3.9.4. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Library - Fix** +- [PR #716](https://github.com/twilio/twilio-python/pull/716): Connection pool is full, discarding connection. Thanks to [@lightiverson](https://github.com/lightiverson)! + +**Api** +- Add ie1 as supported region for UserDefinedMessage and UserDefinedMessageSubscription. + +**Flex** +- Adding validated field to `plugin_versions` +- Corrected the data type for `runtime_domain`, `call_recording_webhook_url`, `crm_callback_url`, `crm_fallback_url`, `flex_url` in Flex Configuration +- Making `routing` optional in Create Interactions endpoint + +**Intelligence** +- Expose operator authoring apis to public visibility +- Deleted `language_code` parameter from updating service in v2 **(breaking change)** +- Add read_only_attached_operator_sids to v2 services + +**Numbers** +- Add API endpoint for GET Porting Webhook Configurations By Account SID +- Remove bulk portability api under version `/v1`. **(breaking change)** +- Removed porting_port_in_fetch.json files and move the content into porting_port_in.json files +- Add API endpoint to deleting Webhook Configurations +- Add Get Phone Number by Port in request SID and Phone Number SID api +- Add Create Porting webhook configuration API +- Added bundle_sid and losing_carrier_information fields to Create PortInRequest api to support Japan porting + +**Taskrouter** +- Add back `routing_target` property to tasks +- Add back `ignore_capacity` property to tasks +- Removing `routing_target` property to tasks due to revert +- Removing `ignore_capacity` property to tasks due to revert +- Add `routing_target` property to tasks +- Add `ignore_capacity` property to tasks + +**Trusthub** +- Add new field errors to bundle as part of public API response in customer_profile.json and trust_product.json **(breaking change)** +- Add themeSetId field in compliance_tollfree_inquiry. + +**Verify** +- Update `friendly_name` description on service docs + + +[2024-04-18] Version 9.0.5 +-------------------------- +**Library - Chore** +- [PR #742](https://github.com/twilio/twilio-python/pull/742): [Snyk] Fix for 3 vulnerabilities. Thanks to [@twilio-product-security](https://github.com/twilio-product-security)! + +**Flex** +- Add header `ui_version` to `web_channels` API + +**Messaging** +- Redeploy after failed pipeline + +**Numbers** +- Add Delete Port In request phone number api and Add Delete Port In request api + + +[2024-04-04] Version 9.0.4 +-------------------------- +**Api** +- Correct conference filtering by date_created and date_updated documentation, clarifying that times are UTC. + +**Flex** +- Remove optional parameter from `plugins` and it to `plugin_versions` + +**Lookups** +- Add new `pre_fill` package to the lookup response + +**Messaging** +- Cleanup api.messaging.next-gen from Messaging Services endpoints +- Readd Sending-Window after fixing test failure + +**Verify** +- Add `whatsapp.msg_service_sid` and `whatsapp.from` parameters to create, update, get and list of services endpoints + +**Voice** +- Correct conference filtering by date_created and date_updated documentation, clarifying that times are UTC. + +**Twiml** +- Add new `token_type` value `payment-method` for `Pay` verb + + +[2024-04-01] Version 9.0.3 +-------------------------- +**Api** +- Add property `queue_time` to conference participant resource +- Update RiskCheck documentation +- Correct call filtering by start and end time documentation, clarifying that times are UTC. + +**Flex** +- Adding optional parameter to `plugins` + +**Media** +- Remove API: MediaProcessor + +**Messaging** +- Remove Sending-Window due to test failure +- Add Sending-Window as a response property to Messaging Services, gated by a beta feature flag + +**Numbers** +- Correct valid_until_date field to be visible in Bundles resource +- Adding port_in_status field to the Port In resource and phone_number_status and sid fields to the Port In Phone Number resource + +**Oauth** +- Modified token endpoint response +- Added refresh_token and scope as optional parameter to token endpoint + +**Trusthub** +- Add update inquiry endpoint in compliance_registration. +- Add new field in themeSetId in compliance_registration. + +**Voice** +- Correct call filtering by start and end time documentation, clarifying that times are UTC. + +**Twiml** +- Add support for new Google voices (Q1 2024) for `Say` verb - gu-IN voices +- Add support for new Amazon Polly and Google voices (Q1 2024) for `Say` verb - Niamh (en-IE) and Sofie (da-DK) voices + + +[2024-03-15] Version 9.0.2 +-------------------------- +**Oauth** +- Add new APIs for vendor authorize and token endpoints + + +[2024-03-12] Version 9.0.1 +-------------------------- +**Library - Chore** +- [PR #775](https://github.com/twilio/twilio-python/pull/775): removing preview.understand references. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Correct precedence documentation for application_sid vs status_callback in message creation +- Mark MaxPrice as deprecated + +**Flex** +- Making `plugins` visibility to public + +**Messaging** +- Add new `errors` attribute to the Brand Registration resource. +- Mark `brand_feedback` attribute as deprecated. +- Mark `failure_reason` attribute as deprecated. +- The new `errors` attribute is expected to provide additional information about Brand registration failures and feedback (if any has been provided by The Campaign Registry). Consumers should use this attribute instead of `brand_feedback` and `failure_reason`. + +**Numbers** +- Correcting mount_name for porting port in fetch API + +**Trusthub** +- Add new field in statusCallbackUrl in compliance_registration. +- Add new field in isvRegisteringForSelfOrTenant in compliance_registration. + +**Twiml** +- Expanded description of Action parameter for Message verb + + +[2024-02-27] Version 9.0.0 +-------------------------- +**Note:** This release contains breaking changes, check our [upgrade guide](./UPGRADE.md###-2024-02-20-8xx-to-9xx) for detailed migration notes. + +**Library - Feature** +- [PR #767](https://github.com/twilio/twilio-python/pull/767): Merge branch '9.0.0-rc' into main. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! **(breaking change)** + +**Library - Chore** +- [PR #771](https://github.com/twilio/twilio-python/pull/771): added check for unset values. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #768](https://github.com/twilio/twilio-python/pull/768): cluster tests enabled. Thanks to [@sbansla](https://github.com/sbansla)! + +**Api** +- remove feedback and feedback summary from call resource + +**Flex** +- Adding `routing_properties` to Interactions Channels Participant + +**Lookups** +- Add new `line_status` package to the lookup response +- Remove `live_activity` package from the lookup response **(breaking change)** + +**Messaging** +- Add tollfree multiple rejection reasons response array + +**Trusthub** +- Add ENUM for businessRegistrationAuthority in compliance_registration. **(breaking change)** +- Add new field in isIsvEmbed in compliance_registration. +- Add additional optional fields in compliance_registration for Individual business type. + +**Twiml** +- Add support for new Amazon Polly and Google voices (Q1 2024) for `Say` verb + + +[2024-02-09] Version 8.13.0 +--------------------------- +**Library - Fix** +- [PR #753](https://github.com/twilio/twilio-python/pull/753): added boolean_to_string converter. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Library - Chore** +- [PR #758](https://github.com/twilio/twilio-python/pull/758): disable cluster test. Thanks to [@sbansla](https://github.com/sbansla)! +- [PR #760](https://github.com/twilio/twilio-python/pull/760): run make prettier. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Updated service base url for connect apps and authorized connect apps APIs **(breaking change)** +- Update documentation to reflect RiskCheck GA +- Added optional parameter `CallToken` for create participant api + +**Events** +- Marked as GA + +**Flex** +- Adding `flex_instance_sid` to Flex Configuration +- Adding `provisioning_status` for Email Manager +- Adding `offline_config` to Flex Configuration + +**Insights** +- add flag to restrict access to unapid customers +- decommission voice-qualitystats-endpoint role + +**Intelligence** +- Add text-generation operator (for example conversation summary) results to existing OperatorResults collection. + +**Lookups** +- Remove `carrier` field from `sms_pumping_risk` and leave `carrier_risk_category` **(breaking change)** +- Remove carrier information from call forwarding package **(breaking change)** + +**Messaging** +- Add update instance endpoints to us_app_to_person api +- Add tollfree edit_allowed and edit_reason fields +- Update Phone Number, Short Code, Alpha Sender, US A2P and Channel Sender documentation +- Add DELETE support to Tollfree Verification resource + +**Numbers** +- Add Get Port In request api + +**Push** +- Migrated to new Push API V4 with Resilient Notification Delivery. + +**Serverless** +- Add node18 as a valid Build runtime + +**Taskrouter** +- Add `jitter_buffer_size` param in update reservation +- Add container attribute to task_queue_bulk_real_time_statistics endpoint +- Remove beta_feature check on task_queue_bulk_real_time_statistics endpoint + +**Trusthub** +- Add optional field NotificationEmail to the POST /v1/ComplianceInquiries/Customers/Initialize API +- Add additional optional fields in compliance_tollfree_inquiry.json +- Rename did to tollfree_phone_number in compliance_tollfree_inquiry.json +- Add new optional field notification_email to compliance_tollfree_inquiry.json + +**Verify** +- `Tags` property added again to Public Docs **(breaking change)** +- Remove `Tags` from Public Docs **(breaking change)** +- Add `VerifyEventSubscriptionEnabled` parameter to service create and update endpoints. +- Add `Tags` optional parameter on Verification creation. +- Update Verify TOTP maturity to GA. + + +[2024-01-25] Version 8.12.0 +--------------------------- +**Oauth** +- updated openid discovery endpoint uri **(breaking change)** +- Added device code authorization endpoint +- added oauth JWKS endpoint +- Get userinfo resource +- OpenID discovery resource +- Add new API for token endpoint + + +[2024-01-14] Version 8.11.1 +--------------------------- +**Library - Chore** +- [PR #749](https://github.com/twilio/twilio-python/pull/749): removing webhook test. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Push** +- Migrated to new Push API V4 with Resilient Notification Delivery. + + +[2023-12-14] Version 8.11.0 +--------------------------- +**Library - Chore** +- [PR #741](https://github.com/twilio/twilio-python/pull/741): upgrade to python 3.12. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #740](https://github.com/twilio/twilio-python/pull/740): bump aiohttp. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Updated service base url for connect apps and authorized connect apps APIs **(breaking change)** + +**Events** +- Marked as GA + +**Insights** +- decommission voice-qualitystats-endpoint role + +**Numbers** +- Add Get Port In request api + +**Taskrouter** +- Add `jitter_buffer_size` param in update reservation + +**Trusthub** +- Add additional optional fields in compliance_tollfree_inquiry.json + +**Verify** +- Remove `Tags` from Public Docs **(breaking change)** + + +[2023-12-01] Version 8.10.3 +--------------------------- +**Verify** +- Add `VerifyEventSubscriptionEnabled` parameter to service create and update endpoints. + + +[2023-11-17] Version 8.10.2 +--------------------------- +**Library - Chore** +- [PR #733](https://github.com/twilio/twilio-python/pull/733): bumping aiohttp from 3.8.5 to 3.8.6. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Api** +- Update documentation to reflect RiskCheck GA + +**Messaging** +- Add tollfree edit_allowed and edit_reason fields +- Update Phone Number, Short Code, Alpha Sender, US A2P and Channel Sender documentation + +**Taskrouter** +- Add container attribute to task_queue_bulk_real_time_statistics endpoint + +**Trusthub** +- Rename did to tollfree_phone_number in compliance_tollfree_inquiry.json +- Add new optional field notification_email to compliance_tollfree_inquiry.json + +**Verify** +- Add `Tags` optional parameter on Verification creation. + + +[2023-11-06] Version 8.10.1 +--------------------------- +**Flex** +- Adding `provisioning_status` for Email Manager + +**Intelligence** +- Add text-generation operator (for example conversation summary) results to existing OperatorResults collection. + +**Messaging** +- Add DELETE support to Tollfree Verification resource + +**Serverless** +- Add node18 as a valid Build runtime + +**Verify** +- Update Verify TOTP maturity to GA. + + +[2023-10-19] Version 8.10.0 +--------------------------- +**Library - Fix** +- [PR #730](https://github.com/twilio/twilio-python/pull/730): Requirement changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #727](https://github.com/twilio/twilio-python/pull/727): Requirement changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! +- [PR #726](https://github.com/twilio/twilio-python/pull/726): requirements changes. Thanks to [@tiwarishubham635](https://github.com/tiwarishubham635)! + +**Accounts** +- Updated Safelist metadata to correct the docs. +- Add Global SafeList API changes + +**Api** +- Added optional parameter `CallToken` for create participant api + +**Flex** +- Adding `offline_config` to Flex Configuration + +**Intelligence** +- Deleted `redacted` parameter from fetching transcript in v2 **(breaking change)** + +**Lookups** +- Add new `phone_number_quality_score` package to the lookup response +- Remove `disposable_phone_number_risk` package **(breaking change)** + +**Messaging** +- Update US App To Person documentation with current `message_samples` requirements + +**Taskrouter** +- Remove beta_feature check on task_queue_bulk_real_time_statistics endpoint +- Add `virtual_start_time` property to tasks +- Updating `task_queue_data` format from `map` to `array` in the response of bulk get endpoint of TaskQueue Real Time Statistics API **(breaking change)** + + +[2023-10-05] Version 8.9.1 +-------------------------- +**Library - Chore** +- [PR #721](https://github.com/twilio/twilio-python/pull/721): Drop dependency on `pytz` by using stdlib `datetime.timezone.utc`. Thanks to [@Zac-HD](https://github.com/Zac-HD)! +- [PR #723](https://github.com/twilio/twilio-python/pull/723): twilio help changes. Thanks to [@kridai](https://github.com/kridai)! + +**Library - Fix** +- [PR #724](https://github.com/twilio/twilio-python/pull/724): Update ValidateSslCertificate method. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + +**Lookups** +- Add test api support for Lookup v2 + + +[2023-09-21] Version 8.9.0 +-------------------------- +**Conversations** +- Enable conversation email bindings, email address configurations and email message subjects + +**Flex** +- Adding `console_errors_included` to Flex Configuration field `debugger_integrations` +- Introducing new channel status as `inactive` in modify channel endpoint for leave functionality **(breaking change)** +- Adding `citrix_voice_vdi` to Flex Configuration + +**Taskrouter** +- Add Update Queues, Workers, Workflow Real Time Statistics API to flex-rt-data-api-v2 endpoint +- Add Update Workspace Real Time Statistics API to flex-rt-data-api-v2 endpoint + + +[2023-09-07] Version 8.8.0 +-------------------------- +**Api** +- Make message tagging parameters public **(breaking change)** + +**Flex** +- Adding `agent_conv_end_methods` to Flex Configuration + +**Messaging** +- Mark Mesasging Services fallback_to_long_code feature obsolete + +**Numbers** +- Add Create Port In request api +- Renaming sid for bulk_hosting_sid and remove account_sid response field in numbers/v2/BulkHostedNumberOrders **(breaking change)** + +**Pricing** +- gate resources behind a beta_feature + + +[2023-08-24] Version 8.7.0 +-------------------------- +**Library - Test** +- [PR #719](https://github.com/twilio/twilio-python/pull/719): Update test_webhook.py. Thanks to [@kridai](https://github.com/kridai)! + +**Api** +- Add new property `RiskCheck` for SMS pumping protection feature only (public beta to be available soon): Include this parameter with a value of `disable` to skip any kind of risk check on the respective message request + +**Flex** +- Changing `sid` path param to `sid` in interaction channel participant update endpoint **(breaking change)** + +**Messaging** +- Add Channel Sender api +- Fixing country code docs and removing Zipwhip references + +**Numbers** +- Request status changed in numbers/v2/BulkHostedNumberOrders **(breaking change)** +- Add bulk hosting orders API under version `/v2 + + +[2023-08-10] Version 8.6.0 +-------------------------- +**Insights** +- Normalize annotations parameters in list summary api to be prefixed + +**Numbers** +- Change Bulk_hosted_sid from BHR to BH prefix in HNO and dependent under version `/v2` API's. **(breaking change)** +- Added parameter target_account_sid to portability and account_sid to response body + +**Verify** +- Remove beta feature flag to list attempts API. +- Remove beta feature flag to verifications summary attempts API. + + +[2023-07-27] Version 8.5.1 +-------------------------- +**Api** +- Added `voice-intelligence`, `voice-intelligence-transcription` and `voice-intelligence-operators` to `usage_record` API. +- Added `tts-google` to `usage_record` API. + +**Lookups** +- Add new `disposable_phone_number_risk` package to the lookup response + +**Verify** +- Documentation of list attempts API was improved by correcting `date_created_after` and `date_created_before` expected date format. +- Documentation was improved by correcting `date_created_after` and `date_created_before` expected date format parameter on attempts summary API. +- Documentation was improved by adding `WHATSAPP` as optional valid parameter on attempts summary API. + +**Twiml** +- Added support for he-il inside of ssm_lang.json that was missing +- Added support for he-il language in say.json that was missing +- Add `statusCallback` and `statusCallbackMethod` attributes to ``. + + +[2023-07-13] Version 8.5.0 +-------------------------- +**Library - Fix** +- [PR #718](https://github.com/twilio/twilio-python/pull/718): Create __init__.py for intelligence domain. Thanks to [@AsabuHere](https://github.com/AsabuHere)! + +**Flex** +- Adding `interaction_context_sid` as optional parameter in Interactions API + +**Messaging** +- Making visiblity public for tollfree_verification API + +**Numbers** +- Remove Sms capability property from HNO creation under version `/v2` of HNO API. **(breaking change)** +- Update required properties in LOA creation under version `/v2` of Authorization document API. **(breaking change)** + +**Taskrouter** +- Add api to fetch task queue statistics for multiple TaskQueues + +**Verify** +- Add `RiskCheck` optional parameter on Verification creation. + +**Twiml** +- Add Google Voices and languages + + +[2023-06-28] Version 8.4.0 +-------------------------- +**Lookups** +- Add `reassigned_number` package to the lookup response + +**Numbers** +- Add hosted_number_order under version `/v2`. +- Update properties in Porting and Bulk Porting APIs. **(breaking change)** +- Added bulk Portability API under version `/v1`. +- Added Portability API under version `/v1`. + + +[2023-06-15] Version 8.3.0 +-------------------------- +**Api** +- Added `content_sid` as conditional parameter +- Removed `content_sid` as optional field **(breaking change)** + +**Insights** +- Added `annotation` to list summary output + + +[2023-06-01] Version 8.2.2 +-------------------------- +**Api** +- Add `Trim` to create Conference Participant API + +**Intelligence** +- First public beta release for Voice Intelligence APIs with client libraries + +**Messaging** +- Add new `errors` attribute to us_app_to_person resource. This attribute will provide additional information about campaign registration errors. + + +[2023-05-18] Version 8.2.1 +-------------------------- +**Conversations** +- Added `AddressCountry` parameter to Address Configuration endpoint, to support regional short code addresses +- Added query parameters `start_date`, `end_date` and `state` in list Conversations resource for filtering + +**Insights** +- Added annotations parameters to list summary api + +**Messaging** +- Add GET domainByMessagingService endpoint to linkShortening service +- Add `disable_https` to link shortening domain_config properties + +**Numbers** +- Add bulk_eligibility api under version `/v1`. + + +[2023-05-04] Version 8.2.0 +-------------------------- +**Conversations** +- Remove `start_date`, `end_date` and `state` query parameters from list operation on Conversations resource **(breaking change)** + +**Twiml** +- Add support for new Amazon Polly voices (Q1 2023) for `Say` verb + + +[2023-04-19] Version 8.1.0 +-------------------------- +**Library - Chore** +- [PR #709](https://github.com/twilio/twilio-python/pull/709): Drop `asyncio` from requirements. Thanks to [@setu4993](https://github.com/setu4993)! + +**Library - Docs** +- [PR #705](https://github.com/twilio/twilio-python/pull/705): consolidate. Thanks to [@stern-shawn](https://github.com/stern-shawn)! + +**Messaging** +- Remove `messaging_service_sids` and `messaging_service_sid_action` from domain config endpoint **(breaking change)** +- Add error_code and rejection_reason properties to tollfree verification API response + +**Numbers** +- Added the new Eligibility API under version `/v1`. + + [2023-04-05] Version 8.0.0 -------------------------- **Note:** This release contains breaking changes, check our [upgrade guide](./UPGRADE.md###-2023-04-05-7xx-to-8xx) for detailed migration notes. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a76a0bf826..41cb4474d0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -23,7 +23,7 @@ it can be. If you have questions about how to use `twilio-python`, please see our [docs](./README.md), and if you don't find the answer there, please contact -[help@twilio.com](mailto:help@twilio.com) with any issues you have. +[Twilio Support](https://www.twilio.com/help/contact) with any issues you have. ## Found an Issue? diff --git a/LICENSE b/LICENSE index ca16167a61..6485c1f845 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (C) 2023, Twilio, Inc. +Copyright (C) 2023, Twilio, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in diff --git a/README.md b/README.md index 50cc5509e1..ed277788d1 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ This library supports the following Python implementations: - Python 3.9 - Python 3.10 - Python 3.11 +- Python 3.12 +- Python 3.13 ## Installation @@ -86,6 +88,13 @@ After a brief delay, you will receive the text message on your phone. > **Warning** > 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. + +API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/public_oauth.py) + +Organisation API examples [here](https://github.com/twilio/twilio-python/blob/main/examples/organization_api.py) + ## Use the helper library ### API Credentials @@ -128,7 +137,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 @@ -184,6 +195,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 @@ -197,6 +210,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/UPGRADE.md b/UPGRADE.md index 79bdb48cc5..03c196bf5b 100644 --- a/UPGRADE.md +++ b/UPGRADE.md @@ -3,6 +3,15 @@ _`MAJOR` version bumps will have upgrade notes posted here._ +## [2024-02-20] 8.x.x to 9.x.x +### Overview + +##### Twilio Python Helper Library’s major version 9.0.0 is now available. We ensured that you can upgrade to Python helper Library 9.0.0 version without any breaking changes of existing apis + +Behind the scenes Python Helper is now auto-generated via OpenAPI with this release. This enables us to rapidly add new features and enhance consistency across versions and languages. +We're pleased to inform you that version 9.0.0 adds support for the application/json content type in the request body. + + ## [2023-04-05] 7.x.x to 8.x.x - **Supported Python versions updated** diff --git a/docs/conf.py b/docs/conf.py index 405c2e99af..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" @@ -203,4 +202,4 @@ # -- Options for intersphinx extension --------------------------------------- # Example configuration for intersphinx: refer to the Python standard library. -intersphinx_mapping = {"https://docs.python.org/": None} +intersphinx_mapping = {"python": ("https://docs.python.org/3", None)} 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 new file mode 100644 index 0000000000..0d653c12a4 --- /dev/null +++ b/examples/organization_api.py @@ -0,0 +1,32 @@ +import os + +from twilio.rest import Client +from twilio.credential.orgs_credential_provider import OrgsCredentialProvider + +ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") +API_KEY = os.environ.get("TWILIO_API_KEY") +API_SECRET = os.environ.get("TWILIO_API_SECRET") + +CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID") +CLIENT_SECRET = os.environ.get("CLIENT_SECRET") +ORGS_SID = os.environ.get("ORGS_SID") + + +def example(): + """ + Some example usage of using organization resources + """ + client = Client( + account_sid=ACCOUNT_SID, + credential_provider=OrgsCredentialProvider(CLIENT_ID, CLIENT_SECRET), + ) + + accounts = client.preview_iam.organization( + organization_sid=ORGS_SID + ).accounts.stream() + for record in accounts: + print(record) + + +if __name__ == "__main__": + example() diff --git a/examples/public_oauth.py b/examples/public_oauth.py new file mode 100644 index 0000000000..124531fc46 --- /dev/null +++ b/examples/public_oauth.py @@ -0,0 +1,28 @@ +import os + +from twilio.rest import Client +from twilio.credential.client_credential_provider import ClientCredentialProvider + +ACCOUNT_SID = os.environ.get("TWILIO_ACCOUNT_SID") +MESSAGE_SID = os.environ.get("TWILIO_MESSAGE_SID") + +CLIENT_ID = os.environ.get("TWILIO_CLIENT_ID") +CLIENT_SECRET = os.environ.get("TWILIO_CLIENT_SECRET") + + +def example(): + """ + An example usage of message resource. + """ + client = Client( + account_sid=ACCOUNT_SID, + credential_provider=ClientCredentialProvider(CLIENT_ID, CLIENT_SECRET), + ) + + msg = client.messages(MESSAGE_SID).fetch() + + print(msg) + + +if __name__ == "__main__": + example() diff --git a/requirements.txt b/requirements.txt index 71730f9278..7bc9e41806 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,8 @@ pygments>=2.7.4 # not directly required, pinned by Snyk to avoid a vulnerability -pytz -requests>=2.0.0 +requests>=2.32.2 PyJWT>=2.0.0, <3.0.0 -aiohttp>=3.8.4 -aiohttp-retry>=2.8.3 +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/setup.cfg b/setup.cfg index c8673986ed..4c18756789 100644 --- a/setup.cfg +++ b/setup.cfg @@ -2,7 +2,8 @@ universal = 1 [metadata] -description-file = README.md +long_description = file: README.md +license = MIT [flake8] exclude = ./twilio/rest,./twilio/twiml,./tests/integration diff --git a/setup.py b/setup.py old mode 100755 new mode 100644 index 0216c02d3e..09672cd205 --- a/setup.py +++ b/setup.py @@ -13,15 +13,14 @@ setup( name="twilio", - version="8.0.0", + version="9.10.9", description="Twilio API client and TwiML generator", author="Twilio", - author_email="help@twilio.com", + help_center="https://www.twilio.com/help/contact", url="https://github.com/twilio/twilio-python/", keywords=["twilio", "twiml"], python_requires=">=3.7.0", install_requires=[ - "pytz", "requests >= 2.0.0", "PyJWT >= 2.0.0, < 3.0.0", "aiohttp>=3.8.4", @@ -40,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/cluster/test_cluster.py b/tests/cluster/test_cluster.py index 0ebec8d0bd..0c18428d15 100644 --- a/tests/cluster/test_cluster.py +++ b/tests/cluster/test_cluster.py @@ -12,6 +12,7 @@ def setUp(self): self.api_key = os.environ["TWILIO_API_KEY"] self.api_secret = os.environ["TWILIO_API_SECRET"] self.account_sid = os.environ["TWILIO_ACCOUNT_SID"] + self.assistant_id = os.environ["ASSISTANT_ID"] self.client = Client( username=self.api_key, password=self.api_secret, @@ -24,7 +25,7 @@ def test_send_text_message(self): to=self.to_number, from_=self.from_number, body="hello world" ) self.assertEqual(msg.to, self.to_number) - self.assertEqual(msg._from, self.from_number) + self.assertEqual(msg.from_, self.from_number) self.assertEqual(msg.body, "hello world") self.assertIsNotNone(msg.sid) @@ -65,6 +66,11 @@ def test_list_available_numbers(self): self.assertIsNotNone(toll_free_numbers) self.assertEqual(len(toll_free_numbers), 2) + def test_fetch_assistant(self): + assistant = self.client.assistants.v1.assistants(self.assistant_id).fetch() + self.assertIsNotNone(assistant) + self.assertEqual(assistant.account_sid, self.account_sid) + def test_calling_twiml_string(self): call = self.client.calls.create( to=self.to_number, from_=self.from_number, twiml=str(self.voice_twiml) diff --git a/tests/cluster/test_webhook.py b/tests/cluster/test_webhook.py index 4ac07bad94..307cf3d397 100644 --- a/tests/cluster/test_webhook.py +++ b/tests/cluster/test_webhook.py @@ -1,12 +1,7 @@ import os -import unittest -import time -import _thread -from http.server import BaseHTTPRequestHandler, HTTPServer -from pyngrok import ngrok +from http.server import BaseHTTPRequestHandler from twilio.request_validator import RequestValidator -from twilio.rest import Client class RequestHandler(BaseHTTPRequestHandler): @@ -34,80 +29,81 @@ def process_request(self): ) -class WebhookTest(unittest.TestCase): - def setUp(self): - api_key = os.environ["TWILIO_API_KEY"] - api_secret = os.environ["TWILIO_API_SECRET"] - account_sid = os.environ["TWILIO_ACCOUNT_SID"] - self.client = Client(api_key, api_secret, account_sid) - - portNumber = 7777 - self.validation_server = HTTPServer(("", portNumber), RequestHandler) - self.tunnel = ngrok.connect(portNumber) - self.flow_sid = "" - _thread.start_new_thread(self.start_http_server, ()) - - def start_http_server(self): - self.validation_server.serve_forever() - - def tearDown(self): - self.client.studio.v2.flows(self.flow_sid).delete() - ngrok.kill() - self.validation_server.shutdown() - self.validation_server.server_close() - - def create_studio_flow(self, url, method): - flow = self.client.studio.v2.flows.create( - friendly_name="Python Cluster Test Flow", - status="published", - definition={ - "description": "Studio Flow", - "states": [ - { - "name": "Trigger", - "type": "trigger", - "transitions": [ - { - "next": "httpRequest", - "event": "incomingRequest", - }, - ], - "properties": {}, - }, - { - "name": "httpRequest", - "type": "make-http-request", - "transitions": [], - "properties": { - "method": method, - "content_type": "application/x-www-form-urlencoded;charset=utf-8", - "url": url, - }, - }, - ], - "initial_state": "Trigger", - "flags": { - "allow_concurrent_calls": True, - }, - }, - ) - return flow - - def validate(self, method): - flow = self.create_studio_flow(url=self.tunnel.public_url, method=method) - self.flow_sid = flow.sid - self.client.studio.v2.flows(self.flow_sid).executions.create( - to="to", from_="from" - ) - - def test_get(self): - time.sleep(5) - self.validate("GET") - time.sleep(5) - self.assertEqual(RequestHandler.is_request_valid, True) - - def test_post(self): - time.sleep(5) - self.validate("POST") - time.sleep(5) - self.assertEqual(RequestHandler.is_request_valid, True) +# class WebhookTest(unittest.TestCase): +# def setUp(self): +# api_key = os.environ["TWILIO_API_KEY"] +# api_secret = os.environ["TWILIO_API_SECRET"] +# account_sid = os.environ["TWILIO_ACCOUNT_SID"] +# self.client = Client(api_key, api_secret, account_sid) +# +# portNumber = 7777 +# self.validation_server = HTTPServer(("", portNumber), RequestHandler) +# self.tunnel = ngrok.connect(portNumber) +# self.flow_sid = "" +# _thread.start_new_thread(self.start_http_server, ()) +# +# def start_http_server(self): +# self.validation_server.serve_forever() +# +# def tearDown(self): +# self.client.studio.v2.flows(self.flow_sid).delete() +# ngrok.kill() +# self.validation_server.shutdown() +# self.validation_server.server_close() +# +# def create_studio_flow(self, url, method): +# flow = self.client.studio.v2.flows.create( +# friendly_name="Python Cluster Test Flow", +# status="published", +# definition={ +# "description": "Studio Flow", +# "states": [ +# { +# "name": "Trigger", +# "type": "trigger", +# "transitions": [ +# { +# "next": "httpRequest", +# "event": "incomingRequest", +# }, +# ], +# "properties": {}, +# }, +# { +# "name": "httpRequest", +# "type": "make-http-request", +# "transitions": [], +# "properties": { +# "method": method, +# "content_type": "application/x-www-form-urlencoded;charset=utf-8", +# "url": url, +# }, +# }, +# ], +# "initial_state": "Trigger", +# "flags": { +# "allow_concurrent_calls": True, +# }, +# }, +# ) +# return flow +# +# def validate(self, method): +# flow = self.create_studio_flow(url=self.tunnel.public_url, method=method) +# self.flow_sid = flow.sid +# time.sleep(5) +# self.client.studio.v2.flows(self.flow_sid).executions.create( +# to="to", from_="from" +# ) +# +# def test_get(self): +# time.sleep(5) +# self.validate("GET") +# time.sleep(5) +# self.assertEqual(RequestHandler.is_request_valid, True) +# +# def test_post(self): +# time.sleep(5) +# self.validate("POST") +# time.sleep(5) +# self.assertEqual(RequestHandler.is_request_valid, True) 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_deserialize.py b/tests/unit/base/test_deserialize.py index 9953772471..33f627e838 100644 --- a/tests/unit/base/test_deserialize.py +++ b/tests/unit/base/test_deserialize.py @@ -2,8 +2,6 @@ import unittest from decimal import Decimal -import pytz - from twilio.base import deserialize @@ -21,7 +19,7 @@ def test_not_parsable(self): class Iso8601DateTimeTestCase(unittest.TestCase): def test_parsable(self): actual = deserialize.iso8601_datetime("2015-01-02T03:04:05Z") - expected = datetime.datetime(2015, 1, 2, 3, 4, 5, 0, pytz.utc) + expected = datetime.datetime(2015, 1, 2, 3, 4, 5, 0, datetime.timezone.utc) self.assertEqual(expected, actual) def test_not_parsable(self): diff --git a/tests/unit/base/test_serialize.py b/tests/unit/base/test_serialize.py index 204fe2c2a0..57891a65b7 100644 --- a/tests/unit/base/test_serialize.py +++ b/tests/unit/base/test_serialize.py @@ -90,6 +90,28 @@ def test_list(self): self.assertEqual({}, actual) +class BooleanTestCase(unittest.TestCase): + def test_none(self): + value = None + actual = serialize.boolean_to_string(value) + self.assertIsNone(actual) + + def test_string(self): + value = "True" + actual = serialize.boolean_to_string(value) + self.assertEqual("true", actual) + + def test_bool_true(self): + value = True + actual = serialize.boolean_to_string(value) + self.assertEqual("true", actual) + + def test_bool_false(self): + value = False + actual = serialize.boolean_to_string(value) + self.assertEqual("false", actual) + + class ObjectTestCase(unittest.TestCase): def test_object(self): actual = serialize.object({"twilio": "rocks"}) 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 e599aaaf00..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): @@ -145,6 +146,32 @@ def test_last_request_last_response_exist(self): "testing-unicode: Ω≈ç√, 💩", self.client._test_only_last_response.text ) + def test_request_with_json(self): + self.request_mock.url = "https://api.twilio.com/" + self.request_mock.headers = {"Host": "other.twilio.com"} + + self.client.request( + "doesnt-matter-method", + "doesnt-matter-url", + {"params-value": "params-key"}, + {"json-key": "json-value"}, + {"Content-Type": "application/json"}, + ) + + self.assertIsNotNone(self.client._test_only_last_request) + self.assertEqual( + {"Content-Type": "application/json"}, + self.client._test_only_last_request.headers, + ) + + self.assertIsNotNone(self.client._test_only_last_response) + + if self.client._test_only_last_response is not None: + self.assertEqual(200, self.client._test_only_last_response.status_code) + self.assertEqual( + "testing-unicode: Ω≈ç√, 💩", self.client._test_only_last_response.text + ) + def test_last_response_empty_on_error(self): self.session_mock.send.side_effect = Exception("voltron") @@ -267,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..f2e2affc02 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): diff --git a/twilio/__init__.py b/twilio/__init__.py index d971c18395..f089e67949 100644 --- a/twilio/__init__.py +++ b/twilio/__init__.py @@ -1,2 +1,2 @@ -__version_info__ = ("8", "0", "0") +__version_info__ = ("9", "10", "9") __version__ = ".".join(__version_info__) diff --git a/twilio/auth_strategy/__init__.py b/twilio/auth_strategy/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/twilio/auth_strategy/auth_strategy.py b/twilio/auth_strategy/auth_strategy.py new file mode 100644 index 0000000000..223cbff08f --- /dev/null +++ b/twilio/auth_strategy/auth_strategy.py @@ -0,0 +1,19 @@ +from twilio.auth_strategy.auth_type import AuthType +from abc import abstractmethod + + +class AuthStrategy(object): + def __init__(self, auth_type: AuthType): + self._auth_type = auth_type + + @property + def auth_type(self) -> AuthType: + return self._auth_type + + @abstractmethod + def get_auth_string(self) -> str: + """Return the authentication string.""" + + @abstractmethod + def requires_authentication(self) -> bool: + """Return True if authentication is required, else False.""" diff --git a/twilio/auth_strategy/auth_type.py b/twilio/auth_strategy/auth_type.py new file mode 100644 index 0000000000..61886f925d --- /dev/null +++ b/twilio/auth_strategy/auth_type.py @@ -0,0 +1,12 @@ +from enum import Enum + + +class AuthType(Enum): + ORGS_TOKEN = "orgs_stoken" + NO_AUTH = "noauth" + BASIC = "basic" + API_KEY = "api_key" + CLIENT_CREDENTIALS = "client_credentials" + + def __str__(self): + return self.value diff --git a/twilio/auth_strategy/no_auth_strategy.py b/twilio/auth_strategy/no_auth_strategy.py new file mode 100644 index 0000000000..a5bfd6d27f --- /dev/null +++ b/twilio/auth_strategy/no_auth_strategy.py @@ -0,0 +1,13 @@ +from auth_type import AuthType +from twilio.auth_strategy.auth_strategy import AuthStrategy + + +class NoAuthStrategy(AuthStrategy): + def __init__(self): + super().__init__(AuthType.NO_AUTH) + + def get_auth_string(self) -> str: + return "" + + def requires_authentication(self) -> bool: + return False diff --git a/twilio/auth_strategy/token_auth_strategy.py b/twilio/auth_strategy/token_auth_strategy.py new file mode 100644 index 0000000000..33a8d385cb --- /dev/null +++ b/twilio/auth_strategy/token_auth_strategy.py @@ -0,0 +1,55 @@ +import jwt +import threading +import logging +from datetime import datetime, timezone + +from twilio.auth_strategy.auth_type import AuthType +from twilio.auth_strategy.auth_strategy import AuthStrategy +from twilio.http.token_manager import TokenManager + + +class TokenAuthStrategy(AuthStrategy): + def __init__(self, token_manager: TokenManager): + super().__init__(AuthType.ORGS_TOKEN) + self.token_manager = token_manager + self.token = None + self.lock = threading.Lock() + logging.basicConfig(level=logging.INFO) + self.logger = logging.getLogger(__name__) + + def get_auth_string(self) -> str: + self.fetch_token() + return f"Bearer {self.token}" + + def requires_authentication(self) -> bool: + return True + + def fetch_token(self): + if self.token is None or self.token == "" or self.is_token_expired(self.token): + with self.lock: + if ( + self.token is None + or self.token == "" + or self.is_token_expired(self.token) + ): + self.logger.info("New token fetched for accessing organization API") + self.token = self.token_manager.fetch_access_token() + + def is_token_expired(self, token): + try: + decoded = jwt.decode(token, options={"verify_signature": False}) + exp = decoded.get("exp") + + if exp is None: + return True # No expiration time present, consider it expired + + # 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 + except Exception as e: + print(f"An error occurred: {e}") + return True 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 c9e0f9c487..af5ccdb09c 100644 --- a/twilio/base/client_base.py +++ b/twilio/base/client_base.py @@ -4,10 +4,10 @@ from urllib.parse import urlparse, urlunparse from twilio import __version__ -from twilio.base.exceptions import TwilioException from twilio.http import HttpClient from twilio.http.http_client import TwilioHttpClient from twilio.http.response import Response +from twilio.credential.credential_provider import CredentialProvider class ClientBase(object): @@ -23,6 +23,7 @@ def __init__( environment: Optional[MutableMapping[str, str]] = None, edge: Optional[str] = None, user_agent_extensions: Optional[List[str]] = None, + credential_provider: Optional[CredentialProvider] = None, ): """ Initializes the Twilio Client @@ -33,9 +34,11 @@ 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 """ + environment = environment or os.environ self.username = username or environment.get("TWILIO_ACCOUNT_SID") @@ -48,9 +51,8 @@ def __init__( """ :type : str """ self.user_agent_extensions = user_agent_extensions or [] """ :type : list[str] """ - - if not self.username or not self.password: - raise TwilioException("Credentials are required to create a TwilioClient") + self.credential_provider = credential_provider or None + """ :type : CredentialProvider """ self.account_sid = account_sid or self.username """ :type : str """ @@ -85,15 +87,27 @@ def request( :returns: Response from the Twilio API """ - auth = self.get_auth(auth) headers = self.get_headers(method, headers) - uri = self.get_hostname(uri) + if self.credential_provider: + + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + elif self.username is not None and self.password is not None: + auth = self.get_auth(auth) + else: + auth = None + + if method == "DELETE": + del headers["Accept"] + + uri = self.get_hostname(uri) + filtered_data = self.copy_non_none_values(data) return self.http_client.request( method, uri, params=params, - data=data, + data=filtered_data, headers=headers, auth=auth, timeout=timeout, @@ -132,21 +146,44 @@ async def request_async( "http_client must be asynchronous to support async API requests" ) - auth = self.get_auth(auth) headers = self.get_headers(method, headers) - uri = self.get_hostname(uri) + if method == "DELETE": + del headers["Accept"] + + if self.credential_provider: + auth_strategy = self.credential_provider.to_auth_strategy() + headers["Authorization"] = auth_strategy.get_auth_string() + elif self.username is not None and self.password is not None: + auth = self.get_auth(auth) + else: + auth = None + uri = self.get_hostname(uri) + filtered_data = self.copy_non_none_values(data) return await self.http_client.request( method, uri, params=params, - data=data, + data=filtered_data, headers=headers, auth=auth, timeout=timeout, allow_redirects=allow_redirects, ) + def copy_non_none_values(self, data): + if isinstance(data, dict): + return { + k: self.copy_non_none_values(v) + for k, v in data.items() + if v is not None + } + elif isinstance(data, list): + return [ + self.copy_non_none_values(item) for item in data if item is not None + ] + return data + def get_auth(self, auth: Optional[Tuple[str, str]]) -> Tuple[str, str]: """ Get the request authentication object @@ -184,7 +221,7 @@ def get_headers( # Types, encodings, etc. headers["Accept-Charset"] = "utf-8" - if method == "POST" and "Content-Type" not in headers: + if (method == "POST" or method == "PUT") and ("Content-Type" not in headers): headers["Content-Type"] = "application/x-www-form-urlencoded" if "Accept" not in headers: headers["Accept"] = "application/json" diff --git a/twilio/base/deserialize.py b/twilio/base/deserialize.py index e70ac57390..71226c08f8 100644 --- a/twilio/base/deserialize.py +++ b/twilio/base/deserialize.py @@ -3,13 +3,11 @@ from email.utils import parsedate from typing import Optional, Union -import pytz - ISO8601_DATE_FORMAT = "%Y-%m-%d" ISO8601_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ" -def iso8601_date(s: str) -> Optional[Union[datetime.date, str]]: +def iso8601_date(s: str) -> Union[datetime.date, str]: """ Parses an ISO 8601 date string and returns a UTC date object or the string if the parsing failed. @@ -19,7 +17,7 @@ def iso8601_date(s: str) -> Optional[Union[datetime.date, str]]: try: return ( datetime.datetime.strptime(s, ISO8601_DATE_FORMAT) - .replace(tzinfo=pytz.utc) + .replace(tzinfo=datetime.timezone.utc) .date() ) except (TypeError, ValueError): @@ -28,7 +26,7 @@ def iso8601_date(s: str) -> Optional[Union[datetime.date, str]]: def iso8601_datetime( s: str, -) -> Optional[Union[datetime.datetime, str]]: +) -> Union[datetime.datetime, str]: """ Parses an ISO 8601 datetime string and returns a UTC datetime object, or the string if parsing failed. @@ -36,7 +34,7 @@ def iso8601_datetime( """ try: return datetime.datetime.strptime(s, ISO8601_DATETIME_FORMAT).replace( - tzinfo=pytz.utc + tzinfo=datetime.timezone.utc ) except (TypeError, ValueError): return s @@ -52,10 +50,10 @@ def rfc2822_datetime(s: str) -> Optional[datetime.datetime]: date_tuple = parsedate(s) if date_tuple is None: return None - return datetime.datetime(*date_tuple[:6]).replace(tzinfo=pytz.utc) + return datetime.datetime(*date_tuple[:6]).replace(tzinfo=datetime.timezone.utc) -def decimal(d: Optional[str]) -> Optional[Union[Decimal, str]]: +def decimal(d: Optional[str]) -> Union[Decimal, str]: """ Parses a decimal string into a Decimal :param d: decimal string @@ -65,7 +63,7 @@ def decimal(d: Optional[str]) -> Optional[Union[Decimal, str]]: return Decimal(d, BasicContext) -def integer(i: str) -> Optional[Union[int, str]]: +def integer(i: str) -> Union[int, str]: """ Parses an integer string into an int :param i: integer string 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/page.py b/twilio/base/page.py index 2238528da9..b5b2da7b26 100644 --- a/twilio/base/page.py +++ b/twilio/base/page.py @@ -77,6 +77,8 @@ def load_page(self, payload: Dict[str, Any]): key = keys - self.META_KEYS if len(key) == 1: return payload[key.pop()] + if "Resources" in payload: + return payload["Resources"] raise TwilioException("Page Records can not be deserialized") diff --git a/twilio/base/serialize.py b/twilio/base/serialize.py index 3abc0defef..cea91b04c7 100644 --- a/twilio/base/serialize.py +++ b/twilio/base/serialize.py @@ -61,6 +61,19 @@ def flatten_dict(d, result=None, prv_keys=None): return {} +def boolean_to_string(bool_or_str): + if bool_or_str == values.unset: + return bool_or_str + + if bool_or_str is None: + return bool_or_str + + if isinstance(bool_or_str, str): + return bool_or_str.lower() + + return "true" if bool_or_str else "false" + + def object(obj): """ Return a jsonified string represenation of obj if obj is jsonifiable else 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 64cc601faa..61f9261904 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 @@ -164,9 +185,74 @@ async def fetch_async( timeout=timeout, allow_redirects=allow_redirects, ) - 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 @@ -230,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]]: """ - Parses delete response JSON + 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]]: + """ + 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, @@ -293,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]: @@ -362,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], @@ -461,7 +803,6 @@ def create( timeout=timeout, allow_redirects=allow_redirects, ) - return self._parse_create(method, uri, response) async def create_async( @@ -488,5 +829,70 @@ async def create_async( timeout=timeout, 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/credential/__init__.py b/twilio/credential/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/twilio/credential/client_credential_provider.py b/twilio/credential/client_credential_provider.py new file mode 100644 index 0000000000..656d446395 --- /dev/null +++ b/twilio/credential/client_credential_provider.py @@ -0,0 +1,28 @@ +from twilio.http.client_token_manager import ClientTokenManager +from twilio.base.exceptions import TwilioException +from twilio.credential.credential_provider import CredentialProvider +from twilio.auth_strategy.auth_type import AuthType +from twilio.auth_strategy.token_auth_strategy import TokenAuthStrategy + + +class ClientCredentialProvider(CredentialProvider): + def __init__(self, client_id: str, client_secret: str, token_manager=None): + super().__init__(AuthType.CLIENT_CREDENTIALS) + + if client_id is None or client_secret is None: + raise TwilioException("Client id and Client secret are mandatory") + + self.grant_type = "client_credentials" + self.client_id = client_id + self.client_secret = client_secret + self.token_manager = token_manager + self.auth_strategy = None + + def to_auth_strategy(self): + if self.token_manager is None: + self.token_manager = ClientTokenManager( + self.grant_type, self.client_id, self.client_secret + ) + if self.auth_strategy is None: + self.auth_strategy = TokenAuthStrategy(self.token_manager) + return self.auth_strategy diff --git a/twilio/credential/credential_provider.py b/twilio/credential/credential_provider.py new file mode 100644 index 0000000000..72aafeed47 --- /dev/null +++ b/twilio/credential/credential_provider.py @@ -0,0 +1,13 @@ +from twilio.auth_strategy.auth_type import AuthType + + +class CredentialProvider: + def __init__(self, auth_type: AuthType): + self._auth_type = auth_type + + @property + def auth_type(self) -> AuthType: + return self._auth_type + + def to_auth_strategy(self): + raise NotImplementedError("Subclasses must implement this method") diff --git a/twilio/credential/orgs_credential_provider.py b/twilio/credential/orgs_credential_provider.py new file mode 100644 index 0000000000..e623f52322 --- /dev/null +++ b/twilio/credential/orgs_credential_provider.py @@ -0,0 +1,28 @@ +from twilio.http.orgs_token_manager import OrgTokenManager +from twilio.base.exceptions import TwilioException +from twilio.credential.credential_provider import CredentialProvider +from twilio.auth_strategy.auth_type import AuthType +from twilio.auth_strategy.token_auth_strategy import TokenAuthStrategy + + +class OrgsCredentialProvider(CredentialProvider): + def __init__(self, client_id: str, client_secret: str, token_manager=None): + super().__init__(AuthType.CLIENT_CREDENTIALS) + + if client_id is None or client_secret is None: + raise TwilioException("Client id and Client secret are mandatory") + + self.grant_type = "client_credentials" + self.client_id = client_id + self.client_secret = client_secret + self.token_manager = token_manager + self.auth_strategy = None + + def to_auth_strategy(self): + if self.token_manager is None: + self.token_manager = OrgTokenManager( + self.grant_type, self.client_id, self.client_secret + ) + if self.auth_strategy is None: + self.auth_strategy = TokenAuthStrategy(self.token_manager) + return self.auth_strategy diff --git a/twilio/http/client_token_manager.py b/twilio/http/client_token_manager.py new file mode 100644 index 0000000000..cec693ed06 --- /dev/null +++ b/twilio/http/client_token_manager.py @@ -0,0 +1,41 @@ +from twilio.http.token_manager import TokenManager +from twilio.rest import Client + + +class ClientTokenManager(TokenManager): + """ + Client Token Manager + """ + + def __init__( + self, + grant_type: str, + client_id: str, + client_secret: str, + code: str = None, + redirect_uri: str = None, + audience: str = None, + refreshToken: str = None, + scope: str = None, + ): + self.grant_type = grant_type + self.client_id = client_id + self.client_secret = client_secret + self.code = code + self.redirect_uri = redirect_uri + self.audience = audience + self.refreshToken = refreshToken + self.scope = scope + self.client = Client() + + def fetch_access_token(self): + token_instance = self.client.oauth.v2.token.create( + grant_type=self.grant_type, + client_id=self.client_id, + client_secret=self.client_secret, + code=self.code, + redirect_uri=self.redirect_uri, + audience=self.audience, + scope=self.scope, + ) + return token_instance.access_token diff --git a/twilio/http/http_client.py b/twilio/http/http_client.py index bfc38feaf7..2f2d363535 100644 --- a/twilio/http/http_client.py +++ b/twilio/http/http_client.py @@ -1,3 +1,4 @@ +import os import logging from typing import Dict, Optional, Tuple @@ -27,11 +28,10 @@ def __init__( ): """ Constructor for the TwilioHttpClient - :param pool_connections :param request_hooks :param timeout: Timeout for the requests. - Timeout should never be zero (0) or less. + Timeout should never be zero (0) or less :param logger :param proxy: Http proxy for the requests session :param max_retries: Maximum number of retries each request should attempt @@ -40,7 +40,10 @@ 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)) - + elif self.session is not None: + self.session.mount( + "https://", HTTPAdapter(pool_maxsize=min(32, os.cpu_count() + 4)) + ) self.request_hooks = request_hooks or hooks.default_hooks() self.proxy = proxy if proxy else {} @@ -65,10 +68,10 @@ def request( :param headers: HTTP Headers to send with the request :param auth: Basic Auth arguments :param timeout: Socket/Read timeout for the request - :param allow_redirects: Whether or not to allow redirects + :param allow_redirects: Whether to allow redirects See the requests documentation for explanation of all these parameters - :return: An http response + :return: An HTTP response """ if timeout is None: timeout = self.timeout @@ -79,14 +82,17 @@ def request( "method": method.upper(), "url": url, "params": params, - "data": data, "headers": headers, "auth": auth, "hooks": self.request_hooks, } - + if headers and headers.get("Content-Type") == "application/json": + kwargs["json"] = data + elif headers and headers.get("Content-Type") == "application/scim+json": + kwargs["json"] = data + else: + kwargs["data"] = data self.log_request(kwargs) - self._test_only_last_response = None session = self.session or Session() request = Request(**kwargs) @@ -97,12 +103,11 @@ def request( settings = session.merge_environment_settings( prepped_request.url, self.proxy, None, None, None ) - response = session.send( prepped_request, allow_redirects=allow_redirects, timeout=timeout, - **settings + **settings, ) self.log_response(response.status_code, response) diff --git a/twilio/http/orgs_token_manager.py b/twilio/http/orgs_token_manager.py new file mode 100644 index 0000000000..c5e406ffd3 --- /dev/null +++ b/twilio/http/orgs_token_manager.py @@ -0,0 +1,41 @@ +from twilio.http.token_manager import TokenManager +from twilio.rest import Client + + +class OrgTokenManager(TokenManager): + """ + Orgs Token Manager + """ + + def __init__( + self, + grant_type: str, + client_id: str, + client_secret: str, + code: str = None, + redirect_uri: str = None, + audience: str = None, + refreshToken: str = None, + scope: str = None, + ): + self.grant_type = grant_type + self.client_id = client_id + self.client_secret = client_secret + self.code = code + self.redirect_uri = redirect_uri + self.audience = audience + self.refreshToken = refreshToken + self.scope = scope + self.client = Client() + + def fetch_access_token(self): + token_instance = self.client.oauth.v2.token.create( + grant_type=self.grant_type, + client_id=self.client_id, + client_secret=self.client_secret, + code=self.code, + redirect_uri=self.redirect_uri, + audience=self.audience, + scope=self.scope, + ) + return token_instance.access_token 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/token_manager.py b/twilio/http/token_manager.py new file mode 100644 index 0000000000..28cc731019 --- /dev/null +++ b/twilio/http/token_manager.py @@ -0,0 +1,7 @@ +from twilio.base.version import Version + + +class TokenManager: + + def fetch_access_token(self, version: Version): + pass diff --git a/twilio/http/validation_client.py b/twilio/http/validation_client.py index c8e211ddf1..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"], @@ -128,11 +127,11 @@ def validate_ssl_certificate(self, client): Validate that a request to the new SSL certificate is successful :return: null on success, raise TwilioRestException if the request fails """ - response = client.request("GET", "https://api.twilio.com:8443") + response = client.request("GET", "https://tls-test.twilio.com:443") if response.status_code < 200 or response.status_code >= 300: raise TwilioRestException( response.status_code, - "https://api.twilio.com:8443", + "https://tls-test.twilio.com:443", "Failed to validate SSL certificate", ) 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 774c0c7adc..fe898b2095 100644 --- a/twilio/rest/__init__.py +++ b/twilio/rest/__init__.py @@ -8,6 +8,7 @@ https://openapi-generator.tech Do not edit the class manually. """ + from typing import TYPE_CHECKING, Optional from twilio.base.client_base import ClientBase @@ -15,7 +16,7 @@ if TYPE_CHECKING: from twilio.rest.accounts import Accounts from twilio.rest.api import Api - from twilio.rest.autopilot import Autopilot + from twilio.rest.assistants import Assistants from twilio.rest.bulkexports import Bulkexports from twilio.rest.chat import Chat from twilio.rest.content import Content @@ -23,12 +24,17 @@ from twilio.rest.events import Events from twilio.rest.flex_api import FlexApi from twilio.rest.frontline_api import FrontlineApi + from twilio.rest.preview_iam import PreviewIam + from twilio.rest.iam import Iam + from twilio.rest.iam import Iam 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.media import Media + 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 @@ -93,6 +99,7 @@ def __init__( environment=None, edge=None, user_agent_extensions=None, + credential_provider=None, ): """ Initializes the Twilio Client @@ -118,12 +125,13 @@ def __init__( environment, edge, user_agent_extensions, + credential_provider, ) # Domains self._accounts: Optional["Accounts"] = None self._api: Optional["Api"] = None - self._autopilot: Optional["Autopilot"] = None + self._assistants: Optional["Assistants"] = None self._bulkexports: Optional["Bulkexports"] = None self._chat: Optional["Chat"] = None self._content: Optional["Content"] = None @@ -131,12 +139,17 @@ def __init__( self._events: Optional["Events"] = None self._flex_api: Optional["FlexApi"] = None self._frontline_api: Optional["FrontlineApi"] = None + self._preview_iam: Optional["PreviewIam"] = None + self._iam: Optional["Iam"] = None + self._iam: Optional["Iam"] = None 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._media: Optional["Media"] = 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 @@ -184,17 +197,17 @@ def api(self) -> "Api": return self._api @property - def autopilot(self) -> "Autopilot": + def assistants(self) -> "Assistants": """ - Access the Autopilot Twilio Domain + Access the Assistants Twilio Domain - :returns: Autopilot Twilio Domain + :returns: Assistants Twilio Domain """ - if self._autopilot is None: - from twilio.rest.autopilot import Autopilot + if self._assistants is None: + from twilio.rest.assistants import Assistants - self._autopilot = Autopilot(self) - return self._autopilot + self._assistants = Assistants(self) + return self._assistants @property def bulkexports(self) -> "Bulkexports": @@ -287,6 +300,45 @@ def frontline_api(self) -> "FrontlineApi": self._frontline_api = FrontlineApi(self) return self._frontline_api + @property + def preview_iam(self) -> "PreviewIam": + """ + Access the PreviewIam Twilio Domain + + :returns: PreviewIam Twilio Domain + """ + if self._preview_iam is None: + from twilio.rest.preview_iam import PreviewIam + + self._preview_iam = PreviewIam(self) + return self._preview_iam + + @property + def iam(self) -> "Iam": + """ + Access the Iam Twilio Domain + + :returns: Iam Twilio Domain + """ + if self._iam is None: + from twilio.rest.iam import Iam + + self._iam = Iam(self) + return self._iam + + @property + def iam(self) -> "Iam": + """ + Access the Iam Twilio Domain + + :returns: Iam Twilio Domain + """ + if self._iam is None: + from twilio.rest.iam import Iam + + self._iam = Iam(self) + return self._iam + @property def insights(self) -> "Insights": """ @@ -300,6 +352,19 @@ def insights(self) -> "Insights": self._insights = Insights(self) return self._insights + @property + def intelligence(self) -> "Intelligence": + """ + Access the Intelligence Twilio Domain + + :returns: Intelligence Twilio Domain + """ + if self._intelligence is None: + from twilio.rest.intelligence import Intelligence + + self._intelligence = Intelligence(self) + return self._intelligence + @property def ip_messaging(self) -> "IpMessaging": """ @@ -313,6 +378,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": """ @@ -327,17 +405,30 @@ def lookups(self) -> "Lookups": return self._lookups @property - def media(self) -> "Media": + def marketplace(self) -> "Marketplace": """ - Access the Media Twilio Domain + Access the Marketplace Twilio Domain - :returns: Media Twilio Domain + :returns: Marketplace Twilio Domain """ - if self._media is None: - from twilio.rest.media import Media + if self._marketplace is None: + from twilio.rest.marketplace import Marketplace - self._media = Media(self) - return self._media + 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": @@ -352,19 +443,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/AccountsBase.py b/twilio/rest/accounts/AccountsBase.py index a89be84161..e9ac0d589d 100644 --- a/twilio/rest/accounts/AccountsBase.py +++ b/twilio/rest/accounts/AccountsBase.py @@ -17,6 +17,7 @@ class AccountsBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Accounts Domain diff --git a/twilio/rest/accounts/v1/__init__.py b/twilio/rest/accounts/v1/__init__.py index c4b24d0391..8be121c71e 100644 --- a/twilio/rest/accounts/v1/__init__.py +++ b/twilio/rest/accounts/v1/__init__.py @@ -16,11 +16,16 @@ from twilio.base.version import Version from twilio.base.domain import Domain from twilio.rest.accounts.v1.auth_token_promotion import AuthTokenPromotionList +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 class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Accounts @@ -29,7 +34,11 @@ def __init__(self, domain: Domain): """ super().__init__(domain, "v1") self._auth_token_promotion: Optional[AuthTokenPromotionList] = None + 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 @property @@ -38,12 +47,36 @@ def auth_token_promotion(self) -> AuthTokenPromotionList: self._auth_token_promotion = AuthTokenPromotionList(self) return self._auth_token_promotion + @property + def bulk_consents(self) -> BulkConsentsList: + if self._bulk_consents is None: + self._bulk_consents = BulkConsentsList(self) + return self._bulk_consents + + @property + def bulk_contacts(self) -> BulkContactsList: + if self._bulk_contacts is None: + self._bulk_contacts = BulkContactsList(self) + return self._bulk_contacts + @property def credentials(self) -> CredentialList: if self._credentials is None: 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: + self._safelist = SafelistList(self) + return self._safelist + @property def secondary_auth_token(self) -> SecondaryAuthTokenList: if self._secondary_auth_token is None: diff --git a/twilio/rest/accounts/v1/auth_token_promotion.py b/twilio/rest/accounts/v1/auth_token_promotion.py index 0dbf1eb752..c60ea48baa 100644 --- a/twilio/rest/accounts/v1/auth_token_promotion.py +++ b/twilio/rest/accounts/v1/auth_token_promotion.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class AuthTokenPromotionInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the secondary Auth Token was created for. :ivar auth_token: The promoted Auth Token that must be used to authenticate future API requests. @@ -79,6 +78,24 @@ async def update_async(self) -> "AuthTokenPromotionInstance": """ return await self._proxy.update_async() + def update_with_http_info(self) -> ApiResponse: + """ + Update the AuthTokenPromotionInstance 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 AuthTokenPromotionInstance 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 @@ -90,6 +107,7 @@ def __repr__(self) -> str: class AuthTokenPromotionContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the AuthTokenPromotionContext @@ -100,6 +118,23 @@ def __init__(self, version: Version): self._uri = "/AuthTokens/Promote" + def _update(self) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def update(self) -> AuthTokenPromotionInstance: """ Update the AuthTokenPromotionInstance @@ -107,15 +142,36 @@ def update(self) -> AuthTokenPromotionInstance: :returns: The updated AuthTokenPromotionInstance """ + payload, _, _ = self._update() + return AuthTokenPromotionInstance(self._version, payload) + + def update_with_http_info(self) -> ApiResponse: + """ + Update the AuthTokenPromotionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update() + instance = AuthTokenPromotionInstance(self._version, payload) + 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({}) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Accept"] = "application/json" - return AuthTokenPromotionInstance(self._version, payload) + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def update_async(self) -> AuthTokenPromotionInstance: """ @@ -124,15 +180,19 @@ async def update_async(self) -> AuthTokenPromotionInstance: :returns: The updated AuthTokenPromotionInstance """ - data = values.of({}) + payload, _, _ = await self._update_async() + return AuthTokenPromotionInstance(self._version, payload) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + async def update_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to update the AuthTokenPromotionInstance and return response metadata - return AuthTokenPromotionInstance(self._version, payload) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async() + instance = AuthTokenPromotionInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -145,6 +205,7 @@ def __repr__(self) -> str: class AuthTokenPromotionList(ListResource): + def __init__(self, version: Version): """ Initialize the AuthTokenPromotionList diff --git a/twilio/rest/accounts/v1/bulk_consents.py b/twilio/rest/accounts/v1/bulk_consents.py new file mode 100644 index 0000000000..423b8ed7eb --- /dev/null +++ b/twilio/rest/accounts/v1/bulk_consents.py @@ -0,0 +1,155 @@ +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 +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 BulkConsentsInstance(InstanceResource): + """ + :ivar items: A list of objects where each object represents the result of processing a `correlation_id`. Each object contains the following fields: `correlation_id`, a unique 32-character UUID that maps the response to the original request; `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.items: Optional[Dict[str, object]] = payload.get("items") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class BulkConsentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkConsentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Consents/Bulk" + + def _create(self, items: List[object]) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Items": serialize.map(items, 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.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) + + def create_with_http_info(self, items: List[object]) -> ApiResponse: + """ + 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 = 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( + { + "Items": serialize.map(items, 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.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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/accounts/v1/bulk_contacts.py b/twilio/rest/accounts/v1/bulk_contacts.py new file mode 100644 index 0000000000..4ede446a9e --- /dev/null +++ b/twilio/rest/accounts/v1/bulk_contacts.py @@ -0,0 +1,155 @@ +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 +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 BulkContactsInstance(InstanceResource): + """ + :ivar items: A list of objects where each object represents the result of processing a `correlation_id`. Each object contains the following fields: `correlation_id`, a unique 32-character UUID that maps the response to the original request; `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.items: Optional[Dict[str, object]] = payload.get("items") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class BulkContactsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkContactsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Contacts/Bulk" + + def _create(self, items: List[object]) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Items": serialize.map(items, 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.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) + + def create_with_http_info(self, items: List[object]) -> ApiResponse: + """ + 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 = 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( + { + "Items": serialize.map(items, 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.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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/accounts/v1/credential/__init__.py b/twilio/rest/accounts/v1/credential/__init__.py index d76ce584f3..e9c4653f0c 100644 --- a/twilio/rest/accounts/v1/credential/__init__.py +++ b/twilio/rest/accounts/v1/credential/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -24,6 +23,7 @@ class CredentialList(ListResource): + def __init__(self, version: Version): """ Initialize the CredentialList diff --git a/twilio/rest/accounts/v1/credential/aws.py b/twilio/rest/accounts/v1/credential/aws.py index 0e17164ecb..0c81106aec 100644 --- a/twilio/rest/accounts/v1/credential/aws.py +++ b/twilio/rest/accounts/v1/credential/aws.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class AwsInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the AWS resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AWS resource. @@ -53,6 +52,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AwsContext] = None @property @@ -88,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 @@ -106,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 @@ -132,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 @@ -143,6 +207,7 @@ def __repr__(self) -> str: class AwsContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the AwsContext @@ -158,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 @@ -165,9 +244,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -177,9 +278,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AwsInstance 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) -> AwsInstance: @@ -189,17 +314,43 @@ def fetch(self) -> AwsInstance: :returns: The fetched AwsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AwsInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AwsInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AwsInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AwsInstance: """ @@ -208,64 +359,130 @@ async def fetch_async(self) -> AwsInstance: :returns: The fetched AwsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + 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( { "FriendlyName": friendly_name, } ) + 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, + 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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 + ) -> 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 @@ -277,12 +494,14 @@ def __repr__(self) -> str: class AwsPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AwsInstance: """ Build an instance of AwsInstance :param payload: Payload response from the API """ + return AwsInstance(self._version, payload) def __repr__(self) -> str: @@ -295,6 +514,7 @@ def __repr__(self) -> str: class AwsList(ListResource): + def __init__(self, version: Version): """ Initialize the AwsList @@ -306,6 +526,36 @@ def __init__(self, version: Version): self._uri = "/Credentials/AWS" + def _create( + self, + credentials: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Credentials": credentials, + "FriendlyName": friendly_name, + "AccountSid": account_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, credentials: str, @@ -321,6 +571,49 @@ def create( :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( { "Credentials": credentials, @@ -328,14 +621,15 @@ def create( "AccountSid": account_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AwsInstance(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, @@ -352,21 +646,35 @@ async def create_async( :returns: The created AwsInstance """ - data = values.of( - { - "Credentials": credentials, - "FriendlyName": friendly_name, - "AccountSid": account_sid, - } + payload, _, _ = await self._create_async( + credentials=credentials, + friendly_name=friendly_name, + account_sid=account_sid, ) + return AwsInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return AwsInstance(self._version, payload) + :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, @@ -418,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, @@ -437,6 +795,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -463,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( @@ -471,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, @@ -495,7 +905,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 AwsPage(self._version, response) async def page_async( @@ -522,11 +938,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 f78a6728c1..1e5333fe17 100644 --- a/twilio/rest/accounts/v1/credential/public_key.py +++ b/twilio/rest/accounts/v1/credential/public_key.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class PublicKeyInstance(InstanceResource): - """ :ivar sid: The unique string that that we created to identify the PublicKey resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Credential that the PublicKey resource belongs to. @@ -53,6 +52,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PublicKeyContext] = None @property @@ -88,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 @@ -106,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": @@ -134,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 @@ -145,6 +209,7 @@ def __repr__(self) -> str: class PublicKeyContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the PublicKeyContext @@ -160,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 @@ -167,9 +246,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -179,9 +280,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PublicKeyInstance 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) -> PublicKeyInstance: @@ -191,17 +316,43 @@ def fetch(self) -> PublicKeyInstance: :returns: The fetched PublicKeyInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return PublicKeyInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PublicKeyInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> PublicKeyInstance: """ @@ -210,17 +361,50 @@ async def fetch_async(self) -> PublicKeyInstance: :returns: The fetched PublicKeyInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return PublicKeyInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return PublicKeyInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the PublicKeyInstance and return response metadata + + + :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( + { + "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, friendly_name: Union[str, object] = values.unset @@ -232,19 +416,47 @@ def update( :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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + 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 @@ -256,19 +468,24 @@ async def update_async( :returns: The updated PublicKeyInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - } - ) + payload, _, _ = await self._update_async(friendly_name=friendly_name) + return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return PublicKeyInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -281,12 +498,14 @@ def __repr__(self) -> str: class PublicKeyPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> PublicKeyInstance: """ Build an instance of PublicKeyInstance :param payload: Payload response from the API """ + return PublicKeyInstance(self._version, payload) def __repr__(self) -> str: @@ -299,6 +518,7 @@ def __repr__(self) -> str: class PublicKeyList(ListResource): + def __init__(self, version: Version): """ Initialize the PublicKeyList @@ -310,6 +530,36 @@ def __init__(self, version: Version): self._uri = "/Credentials/PublicKeys" + def _create( + self, + public_key: str, + friendly_name: Union[str, object] = values.unset, + account_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PublicKey": public_key, + "FriendlyName": friendly_name, + "AccountSid": account_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, public_key: str, @@ -325,6 +575,45 @@ def create( :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( { "PublicKey": public_key, @@ -332,14 +621,15 @@ def create( "AccountSid": account_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return PublicKeyInstance(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, @@ -356,21 +646,31 @@ async def create_async( :returns: The created PublicKeyInstance """ - data = values.of( - { - "PublicKey": public_key, - "FriendlyName": friendly_name, - "AccountSid": account_sid, - } + payload, _, _ = await self._create_async( + public_key=public_key, friendly_name=friendly_name, account_sid=account_sid ) + return PublicKeyInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return PublicKeyInstance(self._version, payload) + :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, @@ -422,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, @@ -441,6 +791,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -467,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( @@ -475,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, @@ -499,7 +901,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 PublicKeyPage(self._version, response) async def page_async( @@ -526,11 +934,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 new file mode 100644 index 0000000000..f7e7912dde --- /dev/null +++ b/twilio/rest/accounts/v1/safelist.py @@ -0,0 +1,341 @@ +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, 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 SafelistInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the SafeList resource. + :ivar phone_number: The phone number or phone number 1k prefix in SafeList. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.phone_number: Optional[str] = payload.get("phone_number") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SafelistList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SafelistList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SafeList/Numbers" + + def _create(self, phone_number: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PhoneNumber": phone_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, 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) + + def create_with_http_info(self, phone_number: str) -> ApiResponse: + """ + Create the SafelistInstance and return response metadata + + :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 = 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( + { + "PhoneNumber": phone_number, + } + ) + 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) -> 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) + + 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 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"}) + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + def delete(self, phone_number: Union[str, object] = values.unset) -> bool: + """ + Delete the 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, _, _ = 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( + { + "PhoneNumber": phone_number, + } + ) + return await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers, params=params + ) + + async def delete_async( + self, phone_number: Union[str, object] = values.unset + ) -> bool: + """ + Asynchronously delete the 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"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers, params=params + ) + + def fetch( + self, phone_number: Union[str, object] = values.unset + ) -> SafelistInstance: + """ + 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, _, _ = 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" + + params = values.of( + { + "PhoneNumber": phone_number, + } + ) + + 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/accounts/v1/secondary_auth_token.py b/twilio/rest/accounts/v1/secondary_auth_token.py index 76b09a764e..9d79a739d7 100644 --- a/twilio/rest/accounts/v1/secondary_auth_token.py +++ b/twilio/rest/accounts/v1/secondary_auth_token.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class SecondaryAuthTokenInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the secondary Auth Token was created for. :ivar date_created: The date and time in UTC when the resource was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. @@ -79,6 +78,24 @@ async def create_async(self) -> "SecondaryAuthTokenInstance": """ return await self._proxy.create_async() + def create_with_http_info(self) -> ApiResponse: + """ + Create the SecondaryAuthTokenInstance 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 SecondaryAuthTokenInstance 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 SecondaryAuthTokenInstance @@ -97,6 +114,24 @@ async def delete_async(self) -> bool: """ return await self._proxy.delete_async() + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SecondaryAuthTokenInstance 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 SecondaryAuthTokenInstance 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 @@ -108,6 +143,7 @@ def __repr__(self) -> str: class SecondaryAuthTokenContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the SecondaryAuthTokenContext @@ -118,6 +154,23 @@ def __init__(self, version: Version): self._uri = "/AuthTokens/Secondary" + 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) -> SecondaryAuthTokenInstance: """ Create the SecondaryAuthTokenInstance @@ -125,11 +178,36 @@ def create(self) -> SecondaryAuthTokenInstance: :returns: The created SecondaryAuthTokenInstance """ + payload, _, _ = self._create() + return SecondaryAuthTokenInstance(self._version, payload) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the SecondaryAuthTokenInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = SecondaryAuthTokenInstance(self._version, payload) + 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({}) - payload = self._version.create(method="POST", uri=self._uri, data=data) + headers["Accept"] = "application/json" - return SecondaryAuthTokenInstance(self._version, payload) + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) async def create_async(self) -> SecondaryAuthTokenInstance: """ @@ -138,13 +216,33 @@ async def create_async(self) -> SecondaryAuthTokenInstance: :returns: The created SecondaryAuthTokenInstance """ - data = values.of({}) + payload, _, _ = await self._create_async() + return SecondaryAuthTokenInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data - ) + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the SecondaryAuthTokenInstance and return response metadata - return SecondaryAuthTokenInstance(self._version, payload) + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = SecondaryAuthTokenInstance(self._version, payload) + 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: """ @@ -153,9 +251,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the SecondaryAuthTokenInstance 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: @@ -165,10 +285,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SecondaryAuthTokenInstance 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 __repr__(self) -> str: """ @@ -181,6 +309,7 @@ def __repr__(self) -> str: class SecondaryAuthTokenList(ListResource): + def __init__(self, version: Version): """ Initialize the SecondaryAuthTokenList diff --git a/twilio/rest/api/ApiBase.py b/twilio/rest/api/ApiBase.py index 417bc0d0df..e53535ab3f 100644 --- a/twilio/rest/api/ApiBase.py +++ b/twilio/rest/api/ApiBase.py @@ -17,6 +17,7 @@ class ApiBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Api Domain diff --git a/twilio/rest/api/v2010/__init__.py b/twilio/rest/api/v2010/__init__.py index fe5c45c51e..2efb4ff3d0 100644 --- a/twilio/rest/api/v2010/__init__.py +++ b/twilio/rest/api/v2010/__init__.py @@ -20,6 +20,7 @@ class V2010(Version): + def __init__(self, domain: Domain): """ Initialize the V2010 version of Api diff --git a/twilio/rest/api/v2010/account/__init__.py b/twilio/rest/api/v2010/account/__init__.py index fafb4f573c..0aa9ecd0b0 100644 --- a/twilio/rest/api/v2010/account/__init__.py +++ b/twilio/rest/api/v2010/account/__init__.py @@ -12,10 +12,10 @@ 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 @@ -52,6 +52,7 @@ class AccountInstance(InstanceResource): + class Status(object): ACTIVE = "active" SUSPENDED = "suspended" @@ -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: """ @@ -349,6 +405,7 @@ def __repr__(self) -> str: class AccountContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the AccountContext @@ -389,6 +446,22 @@ def __init__(self, version: Version, sid: str): self._usage: Optional[UsageList] = None self._validation_requests: Optional[ValidationRequestList] = None + 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) -> AccountInstance: """ Fetch the AccountInstance @@ -396,17 +469,43 @@ def fetch(self) -> AccountInstance: :returns: The fetched AccountInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AccountInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccountInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AccountInstance: """ @@ -415,17 +514,55 @@ async def fetch_async(self) -> AccountInstance: :returns: The fetched AccountInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AccountInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AccountInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + } + ) + 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, @@ -440,20 +577,55 @@ def update( :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( { "FriendlyName": friendly_name, "Status": status, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AccountInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -468,20 +640,29 @@ async def update_async( :returns: The updated AccountInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Status": status, - } + payload, _, _ = await self._update_async( + friendly_name=friendly_name, status=status ) + return AccountInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return AccountInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -782,12 +963,14 @@ def __repr__(self) -> str: class AccountPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: """ Build an instance of AccountInstance :param payload: Payload response from the API """ + return AccountInstance(self._version, payload) def __repr__(self) -> str: @@ -800,6 +983,7 @@ def __repr__(self) -> str: class AccountList(ListResource): + def __init__(self, version: Version): """ Initialize the AccountList @@ -811,6 +995,29 @@ def __init__(self, version: Version): self._uri = "/Accounts.json" + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + 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 ) -> AccountInstance: @@ -821,19 +1028,47 @@ def create( :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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AccountInstance(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, friendly_name: Union[str, object] = values.unset @@ -845,19 +1080,24 @@ async def create_async( :returns: The created AccountInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - } - ) + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return AccountInstance(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: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the AccountInstance and return response metadata - return AccountInstance(self._version, payload) + :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, @@ -921,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, @@ -944,6 +1244,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -976,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( @@ -986,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, @@ -1016,7 +1380,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 AccountPage(self._version, response) async def page_async( @@ -1049,11 +1419,97 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 224601e270..c309d54844 100644 --- a/twilio/rest/api/v2010/account/address/__init__.py +++ b/twilio/rest/api/v2010/account/address/__init__.py @@ -12,10 +12,10 @@ 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 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 +27,6 @@ class AddressInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is responsible for the Address resource. :ivar city: The city in which the address is located. @@ -81,6 +80,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[AddressContext] = None @property @@ -117,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 @@ -135,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, @@ -150,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. @@ -189,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. @@ -213,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: """ @@ -231,6 +345,7 @@ def __repr__(self) -> str: class AddressContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the AddressContext @@ -252,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 @@ -259,9 +388,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -271,9 +422,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressInstance 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) -> AddressInstance: @@ -283,18 +458,45 @@ def fetch(self) -> AddressInstance: :returns: The fetched AddressInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return AddressInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddressInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AddressInstance: """ @@ -303,20 +505,31 @@ async def fetch_async(self) -> AddressInstance: :returns: The fetched AddressInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AddressInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return AddressInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, customer_name: Union[str, object] = values.unset, @@ -327,22 +540,14 @@ 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( { "FriendlyName": friendly_name, @@ -351,18 +556,59 @@ def update( "City": city, "Region": region, "PostalCode": postal_code, - "EmergencyEnabled": emergency_enabled, - "AutoCorrectAddress": auto_correct_address, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), "StreetSecondary": street_secondary, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -370,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, @@ -381,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. @@ -395,8 +641,46 @@ 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( { "FriendlyName": friendly_name, @@ -405,37 +689,124 @@ async def update_async( "City": city, "Region": region, "PostalCode": postal_code, - "EmergencyEnabled": emergency_enabled, - "AutoCorrectAddress": auto_correct_address, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), "StreetSecondary": street_secondary, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AddressInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) + headers["Accept"] = "application/json" - @property - def dependent_phone_numbers(self) -> DependentPhoneNumberList: - """ - Access the dependent_phone_numbers - """ - if self._dependent_phone_numbers is None: - self._dependent_phone_numbers = DependentPhoneNumberList( - self._version, - self._solution["account_sid"], - self._solution["sid"], - ) - return self._dependent_phone_numbers + 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, + 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 + """ + if self._dependent_phone_numbers is None: + self._dependent_phone_numbers = DependentPhoneNumberList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._dependent_phone_numbers def __repr__(self) -> str: """ @@ -448,12 +819,14 @@ def __repr__(self) -> str: class AddressPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AddressInstance: """ Build an instance of AddressInstance :param payload: Payload response from the API """ + return AddressInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -468,6 +841,7 @@ def __repr__(self) -> str: class AddressList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the AddressList @@ -484,6 +858,50 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Addresses.json".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "CustomerName": customer_name, + "Street": street, + "City": city, + "Region": region, + "PostalCode": postal_code, + "IsoCountry": iso_country, + "FriendlyName": friendly_name, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), + "StreetSecondary": street_secondary, + } + ) + 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, customer_name: str, @@ -506,13 +924,95 @@ def create( :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 """ + 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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "CustomerName": customer_name, @@ -522,20 +1022,19 @@ def create( "PostalCode": postal_code, "IsoCountry": iso_country, "FriendlyName": friendly_name, - "EmergencyEnabled": emergency_enabled, - "AutoCorrectAddress": auto_correct_address, + "EmergencyEnabled": serialize.boolean_to_string(emergency_enabled), + "AutoCorrectAddress": serialize.boolean_to_string(auto_correct_address), "StreetSecondary": street_secondary, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AddressInstance( - self._version, payload, account_sid=self._solution["account_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( @@ -560,42 +1059,80 @@ 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 """ - data = values.of( - { - "CustomerName": customer_name, - "Street": street, - "City": city, - "Region": region, - "PostalCode": postal_code, - "IsoCountry": iso_country, - "FriendlyName": friendly_name, - "EmergencyEnabled": emergency_enabled, - "AutoCorrectAddress": auto_correct_address, - "StreetSecondary": street_secondary, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return AddressInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return AddressInstance( + 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, @@ -608,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 @@ -622,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"], ) @@ -632,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, @@ -644,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 @@ -658,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, @@ -679,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 @@ -689,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, @@ -703,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, @@ -714,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 @@ -724,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, @@ -750,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 @@ -761,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, @@ -768,13 +1471,20 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AddressPage(self._version, response, self._solution) + 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 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, @@ -786,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 @@ -797,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, @@ -804,10 +1516,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return AddressPage(self._version, response, self._solution) + 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: """ @@ -819,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: """ @@ -831,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 6e9ff957a0..9a21e34d7c 100644 --- a/twilio/rest/api/v2010/account/address/dependent_phone_number.py +++ b/twilio/rest/api/v2010/account/address/dependent_phone_number.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +24,7 @@ class DependentPhoneNumberInstance(InstanceResource): + class AddressRequirement(object): NONE = "none" ANY = "any" @@ -127,12 +128,14 @@ def __repr__(self) -> str: class DependentPhoneNumberPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> DependentPhoneNumberInstance: """ Build an instance of DependentPhoneNumberInstance :param payload: Payload response from the API """ + return DependentPhoneNumberInstance( self._version, payload, @@ -150,6 +153,7 @@ def __repr__(self) -> str: class DependentPhoneNumberList(ListResource): + def __init__(self, version: Version, account_sid: str, address_sid: str): """ Initialize the DependentPhoneNumberList @@ -220,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, @@ -239,6 +293,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -265,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( @@ -273,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, @@ -297,8 +403,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DependentPhoneNumberPage(self._version, response, self._solution) + 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 DependentPhoneNumberPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -324,10 +438,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return DependentPhoneNumberPage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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: """ @@ -339,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: """ @@ -351,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 5179d5d55b..ba5a7926de 100644 --- a/twilio/rest/api/v2010/account/application.py +++ b/twilio/rest/api/v2010/account/application.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class ApplicationInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Application resource. :ivar api_version: The API version used to start a new TwiML session. @@ -96,6 +95,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ApplicationContext] = None @property @@ -132,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 @@ -150,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, @@ -270,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 @@ -281,6 +437,7 @@ def __repr__(self) -> str: class ApplicationContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the ApplicationContext @@ -300,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 @@ -307,9 +478,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -319,9 +512,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ApplicationInstance 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) -> ApplicationInstance: @@ -331,18 +548,45 @@ def fetch(self) -> ApplicationInstance: :returns: The fetched ApplicationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return ApplicationInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ApplicationInstance: """ @@ -351,20 +595,31 @@ async def fetch_async(self) -> ApplicationInstance: :returns: The fetched ApplicationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ApplicationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return ApplicationInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -382,29 +637,14 @@ 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( { "FriendlyName": friendly_name, @@ -415,31 +655,31 @@ def update( "VoiceFallbackMethod": voice_fallback_method, "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, - "VoiceCallerIdLookup": voice_caller_id_lookup, + "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, - "PublicApplicationConnectEnabled": public_application_connect_enabled, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_enabled + ), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ApplicationInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -459,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. @@ -480,41 +720,292 @@ async def update_async( :returns: The updated ApplicationInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "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": 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, - "PublicApplicationConnectEnabled": public_application_connect_enabled, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ApplicationInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - - def __repr__(self) -> str: + 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"], + ) + + 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, + "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, + "PublicApplicationConnectEnabled": serialize.boolean_to_string( + public_application_connect_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, + 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, + 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, + 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 @@ -525,12 +1016,14 @@ def __repr__(self) -> str: 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, account_sid=self._solution["account_sid"] ) @@ -544,24 +1037,272 @@ def __repr__(self) -> str: return "" -class ApplicationList(ListResource): - def __init__(self, version: Version, account_sid: str): +class ApplicationList(ListResource): + + def __init__(self, version: Version, account_sid: str): + """ + Initialize the ApplicationList + + :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 Application resources to read. + + """ + super().__init__(version) + + # 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) """ - Initialize the ApplicationList - :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 Application resources to read. + 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"}) - """ - super().__init__(version) + headers["Content-Type"] = "application/x-www-form-urlencoded" - # Path Solution - self._solution = { - "account_sid": account_sid, - } - self._uri = "/Accounts/{account_sid}/Applications.json".format(**self._solution) + headers["Accept"] = "application/json" - def create( + 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, voice_url: Union[str, object] = values.unset, @@ -581,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. @@ -602,38 +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": 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": public_application_connect_enabled, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, @@ -651,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. @@ -672,38 +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": 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": public_application_connect_enabled, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, @@ -761,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, @@ -782,6 +1562,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -811,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( @@ -820,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, @@ -847,8 +1685,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ApplicationPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -877,10 +1721,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ApplicationPage(self._version, response, self._solution) + 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: """ @@ -892,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: """ @@ -904,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 4d71766b62..b608e9f141 100644 --- a/twilio/rest/api/v2010/account/authorized_connect_app.py +++ b/twilio/rest/api/v2010/account/authorized_connect_app.py @@ -12,10 +12,9 @@ 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 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 @@ -24,6 +23,7 @@ class AuthorizedConnectAppInstance(InstanceResource): + class Permission(object): GET_ALL = "get-all" POST_ALL = "post-all" @@ -35,8 +35,6 @@ class Permission(object): :ivar connect_app_friendly_name: The name of the Connect App. :ivar connect_app_homepage_url: The public URL for the Connect App. :ivar connect_app_sid: The SID that we assigned to the Connect App. - :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 permissions: The set of permissions that you authorized for the Connect App. Can be: `get-all` or `post-all`. :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. """ @@ -64,21 +62,16 @@ def __init__( "connect_app_homepage_url" ) self.connect_app_sid: Optional[str] = payload.get("connect_app_sid") - 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.permissions: Optional[List["AuthorizedConnectAppInstance.Permission"]] = ( + payload.get("permissions") ) - self.permissions: Optional[ - List["AuthorizedConnectAppInstance.Permission"] - ] = payload.get("permissions") self.uri: Optional[str] = payload.get("uri") self._solution = { "account_sid": account_sid, "connect_app_sid": connect_app_sid or self.connect_app_sid, } + self._context: Optional[AuthorizedConnectAppContext] = None @property @@ -115,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 @@ -126,6 +137,7 @@ def __repr__(self) -> str: class AuthorizedConnectAppContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, connect_app_sid: str): """ Initialize the AuthorizedConnectAppContext @@ -145,6 +157,22 @@ def __init__(self, version: Version, account_sid: str, connect_app_sid: str): **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) -> AuthorizedConnectAppInstance: """ Fetch the AuthorizedConnectAppInstance @@ -152,18 +180,45 @@ def fetch(self) -> AuthorizedConnectAppInstance: :returns: The fetched AuthorizedConnectAppInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AuthorizedConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], ) - return AuthorizedConnectAppInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizedConnectAppInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AuthorizedConnectAppInstance: """ @@ -172,18 +227,29 @@ async def fetch_async(self) -> AuthorizedConnectAppInstance: :returns: The fetched AuthorizedConnectAppInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AuthorizedConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + connect_app_sid=self._solution["connect_app_sid"], ) - return AuthorizedConnectAppInstance( + 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: """ @@ -196,12 +262,14 @@ def __repr__(self) -> str: class AuthorizedConnectAppPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AuthorizedConnectAppInstance: """ Build an instance of AuthorizedConnectAppInstance :param payload: Payload response from the API """ + return AuthorizedConnectAppInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -216,6 +284,7 @@ def __repr__(self) -> str: class AuthorizedConnectAppList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the AuthorizedConnectAppList @@ -284,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, @@ -303,6 +422,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -329,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( @@ -337,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, @@ -361,8 +532,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AuthorizedConnectAppPage(self._version, response, self._solution) + 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 AuthorizedConnectAppPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -388,10 +567,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return AuthorizedConnectAppPage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -403,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: """ @@ -415,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 5645844cfb..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 @@ -12,9 +12,9 @@ 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 @@ -40,7 +40,6 @@ class AvailablePhoneNumberCountryInstance(InstanceResource): - """ :ivar country_code: The [ISO-3166-1](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) country code of the country. :ivar country: The name of the country. @@ -70,6 +69,7 @@ def __init__( "account_sid": account_sid, "country_code": country_code or self.country_code, } + self._context: Optional[AvailablePhoneNumberCountryContext] = None @property @@ -106,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: """ @@ -168,6 +186,7 @@ def __repr__(self) -> str: class AvailablePhoneNumberCountryContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, country_code: str): """ Initialize the AvailablePhoneNumberCountryContext @@ -197,6 +216,22 @@ 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) -> 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) -> AvailablePhoneNumberCountryInstance: """ Fetch the AvailablePhoneNumberCountryInstance @@ -204,18 +239,45 @@ def fetch(self) -> AvailablePhoneNumberCountryInstance: :returns: The fetched AvailablePhoneNumberCountryInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], ) - return AvailablePhoneNumberCountryInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailablePhoneNumberCountryInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AvailablePhoneNumberCountryInstance: """ @@ -224,18 +286,29 @@ async def fetch_async(self) -> AvailablePhoneNumberCountryInstance: :returns: The fetched AvailablePhoneNumberCountryInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AvailablePhoneNumberCountryInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + country_code=self._solution["country_code"], ) - return AvailablePhoneNumberCountryInstance( + 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: @@ -341,6 +414,7 @@ def __repr__(self) -> str: class AvailablePhoneNumberCountryPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> AvailablePhoneNumberCountryInstance: @@ -349,6 +423,7 @@ def get_instance( :param payload: Payload response from the API """ + return AvailablePhoneNumberCountryInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -363,6 +438,7 @@ def __repr__(self) -> str: class AvailablePhoneNumberCountryList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the AvailablePhoneNumberCountryList @@ -431,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, @@ -450,6 +576,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -476,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( @@ -484,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, @@ -508,8 +686,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + 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 AvailablePhoneNumberCountryPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -535,10 +721,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return AvailablePhoneNumberCountryPage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -550,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: """ @@ -562,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 b8e0cee71a..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 @@ -12,9 +12,9 @@ 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 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,7 +23,6 @@ class LocalInstance(InstanceResource): - """ :ivar friendly_name: A formatted version of the phone number. :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. @@ -79,12 +78,14 @@ def __repr__(self) -> str: class LocalPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: """ Build an instance of LocalInstance :param payload: Payload response from the API """ + return LocalInstance( self._version, payload, @@ -102,6 +103,7 @@ def __repr__(self) -> str: class LocalList(ListResource): + def __init__(self, version: Version, account_sid: str, country_code: str): """ Initialize the LocalList @@ -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`. @@ -501,13 +823,19 @@ def page( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -516,15 +844,21 @@ def page( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return LocalPage(self._version, response, self._solution) + 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 LocalPage(self._version, response, solution=self._solution) async def page_async( self, @@ -555,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`. @@ -582,13 +916,19 @@ async def page_async( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -597,17 +937,211 @@ async def page_async( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return LocalPage(self._version, response, self._solution) + 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: """ @@ -619,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: """ @@ -631,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 65e0be2b88..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 @@ -12,9 +12,9 @@ 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 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,7 +23,6 @@ class MachineToMachineInstance(InstanceResource): - """ :ivar friendly_name: A formatted version of the phone number. :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. @@ -79,12 +78,14 @@ def __repr__(self) -> str: class MachineToMachinePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MachineToMachineInstance: """ Build an instance of MachineToMachineInstance :param payload: Payload response from the API """ + return MachineToMachineInstance( self._version, payload, @@ -102,6 +103,7 @@ def __repr__(self) -> str: class MachineToMachineList(ListResource): + def __init__(self, version: Version, account_sid: str, country_code: str): """ Initialize the MachineToMachineList @@ -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`. @@ -501,13 +823,19 @@ def page( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -516,15 +844,21 @@ def page( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MachineToMachinePage(self._version, response, self._solution) + 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 MachineToMachinePage(self._version, response, solution=self._solution) async def page_async( self, @@ -555,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`. @@ -582,13 +916,19 @@ async def page_async( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -597,17 +937,211 @@ async def page_async( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MachineToMachinePage(self._version, response, self._solution) + 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: """ @@ -619,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: """ @@ -631,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 5ef6f891d3..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 @@ -12,9 +12,9 @@ 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 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,7 +23,6 @@ class MobileInstance(InstanceResource): - """ :ivar friendly_name: A formatted version of the phone number. :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. @@ -79,12 +78,14 @@ def __repr__(self) -> str: class MobilePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: """ Build an instance of MobileInstance :param payload: Payload response from the API """ + return MobileInstance( self._version, payload, @@ -102,6 +103,7 @@ def __repr__(self) -> str: class MobileList(ListResource): + def __init__(self, version: Version, account_sid: str, country_code: str): """ Initialize the MobileList @@ -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`. @@ -501,13 +823,19 @@ def page( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -516,15 +844,21 @@ def page( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MobilePage(self._version, response, self._solution) + 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 MobilePage(self._version, response, solution=self._solution) async def page_async( self, @@ -555,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`. @@ -582,13 +916,19 @@ async def page_async( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -597,17 +937,211 @@ async def page_async( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MobilePage(self._version, response, self._solution) + 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: """ @@ -619,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: """ @@ -631,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 8b2edb640c..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 @@ -12,9 +12,9 @@ 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 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,7 +23,6 @@ class NationalInstance(InstanceResource): - """ :ivar friendly_name: A formatted version of the phone number. :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. @@ -79,12 +78,14 @@ def __repr__(self) -> str: class NationalPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> NationalInstance: """ Build an instance of NationalInstance :param payload: Payload response from the API """ + return NationalInstance( self._version, payload, @@ -102,6 +103,7 @@ def __repr__(self) -> str: class NationalList(ListResource): + def __init__(self, version: Version, account_sid: str, country_code: str): """ Initialize the NationalList @@ -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`. @@ -501,13 +823,19 @@ def page( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -516,15 +844,21 @@ def page( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return NationalPage(self._version, response, self._solution) + 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 NationalPage(self._version, response, solution=self._solution) async def page_async( self, @@ -555,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`. @@ -582,13 +916,19 @@ async def page_async( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -597,17 +937,211 @@ async def page_async( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return NationalPage(self._version, response, self._solution) + 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: """ @@ -619,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: """ @@ -631,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 d167c2f039..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 @@ -12,9 +12,9 @@ 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 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,7 +23,6 @@ class SharedCostInstance(InstanceResource): - """ :ivar friendly_name: A formatted version of the phone number. :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. @@ -79,12 +78,14 @@ def __repr__(self) -> str: class SharedCostPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SharedCostInstance: """ Build an instance of SharedCostInstance :param payload: Payload response from the API """ + return SharedCostInstance( self._version, payload, @@ -102,6 +103,7 @@ def __repr__(self) -> str: class SharedCostList(ListResource): + def __init__(self, version: Version, account_sid: str, country_code: str): """ Initialize the SharedCostList @@ -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`. @@ -501,13 +823,19 @@ def page( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -516,15 +844,21 @@ def page( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SharedCostPage(self._version, response, self._solution) + 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 SharedCostPage(self._version, response, solution=self._solution) async def page_async( self, @@ -555,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`. @@ -582,13 +916,19 @@ async def page_async( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -597,17 +937,211 @@ async def page_async( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SharedCostPage(self._version, response, self._solution) + 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: """ @@ -619,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: """ @@ -631,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 aea21d7017..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 @@ -12,9 +12,9 @@ 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 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,7 +23,6 @@ class TollFreeInstance(InstanceResource): - """ :ivar friendly_name: A formatted version of the phone number. :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. @@ -79,12 +78,14 @@ def __repr__(self) -> str: class TollFreePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: """ Build an instance of TollFreeInstance :param payload: Payload response from the API """ + return TollFreeInstance( self._version, payload, @@ -102,6 +103,7 @@ def __repr__(self) -> str: class TollFreeList(ListResource): + def __init__(self, version: Version, account_sid: str, country_code: str): """ Initialize the TollFreeList @@ -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`. @@ -501,13 +823,19 @@ def page( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -516,15 +844,21 @@ def page( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TollFreePage(self._version, response, self._solution) + 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 TollFreePage(self._version, response, solution=self._solution) async def page_async( self, @@ -555,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`. @@ -582,13 +916,19 @@ async def page_async( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -597,17 +937,211 @@ async def page_async( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return TollFreePage(self._version, response, self._solution) + 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: """ @@ -619,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: """ @@ -631,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 fba53f0357..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 @@ -12,9 +12,9 @@ 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 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,7 +23,6 @@ class VoipInstance(InstanceResource): - """ :ivar friendly_name: A formatted version of the phone number. :ivar phone_number: The phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. @@ -79,12 +78,14 @@ def __repr__(self) -> str: class VoipPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> VoipInstance: """ Build an instance of VoipInstance :param payload: Payload response from the API """ + return VoipInstance( self._version, payload, @@ -102,6 +103,7 @@ def __repr__(self) -> str: class VoipList(ListResource): + def __init__(self, version: Version, account_sid: str, country_code: str): """ Initialize the VoipList @@ -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`. @@ -501,13 +823,19 @@ def page( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -516,15 +844,21 @@ def page( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "FaxEnabled": serialize.boolean_to_string(fax_enabled), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return VoipPage(self._version, response, self._solution) + 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 VoipPage(self._version, response, solution=self._solution) async def page_async( self, @@ -555,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`. @@ -582,13 +916,19 @@ async def page_async( { "AreaCode": area_code, "Contains": contains, - "SmsEnabled": sms_enabled, - "MmsEnabled": mms_enabled, - "VoiceEnabled": voice_enabled, - "ExcludeAllAddressRequired": exclude_all_address_required, - "ExcludeLocalAddressRequired": exclude_local_address_required, - "ExcludeForeignAddressRequired": exclude_foreign_address_required, - "Beta": beta, + "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, @@ -597,17 +937,211 @@ async def page_async( "InRateCenter": in_rate_center, "InLata": in_lata, "InLocality": in_locality, - "FaxEnabled": fax_enabled, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return VoipPage(self._version, response, self._solution) + 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: """ @@ -619,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: """ @@ -631,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 e3c2d5e7e4..106e76e33d 100644 --- a/twilio/rest/api/v2010/account/balance.py +++ b/twilio/rest/api/v2010/account/balance.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class BalanceInstance(InstanceResource): - """ :ivar account_sid: The unique SID identifier of the Account. :ivar balance: The balance of the Account, in units specified by the unit parameter. Balance changes may not be reflected immediately. Child accounts do not contain balance information @@ -50,6 +50,7 @@ def __repr__(self) -> str: class BalanceList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the BalanceList @@ -66,30 +67,86 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Balance.json".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) -> BalanceInstance: """ - Asynchronously fetch the BalanceInstance + Fetch the BalanceInstance + :returns: The fetched BalanceInstance """ - payload = self._version.fetch(method="GET", uri=self._uri) - + payload, _, _ = self._fetch() return BalanceInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BalanceInstance and return response metadata + + + :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" + + 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._version.fetch_async(method="GET", uri=self._uri) - + 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 7c969eff7d..23b0121ee4 100644 --- a/twilio/rest/api/v2010/account/call/__init__.py +++ b/twilio/rest/api/v2010/account/call/__init__.py @@ -12,23 +12,22 @@ 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 from twilio.rest.api.v2010.account.call.event import EventList -from twilio.rest.api.v2010.account.call.feedback import FeedbackList -from twilio.rest.api.v2010.account.call.feedback_summary import FeedbackSummaryList from twilio.rest.api.v2010.account.call.notification import NotificationList from twilio.rest.api.v2010.account.call.payment import PaymentList from twilio.rest.api.v2010.account.call.recording import RecordingList from twilio.rest.api.v2010.account.call.siprec import SiprecList from twilio.rest.api.v2010.account.call.stream import StreamList +from twilio.rest.api.v2010.account.call.transcription import TranscriptionList from twilio.rest.api.v2010.account.call.user_defined_message import ( UserDefinedMessageList, ) @@ -38,6 +37,7 @@ class CallInstance(InstanceResource): + class Status(object): QUEUED = "queued" RINGING = "ringing" @@ -54,8 +54,8 @@ class UpdateStatus(object): """ :ivar sid: The unique string that we created to identify this Call resource. - :ivar date_created: The date and time in GMT that this 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 this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_created: The date and time in UTC that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :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 parent_call_sid: The SID that identifies the call that created this leg. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Call resource. :ivar to: The phone number, SIP address, Client identifier or SIM SID 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 `name@company.com`. Client identifiers are formatted `client:name`. SIM SIDs are formatted as `sim:sid`. @@ -64,10 +64,10 @@ class UpdateStatus(object): :ivar from_formatted: The calling phone number, SIP address, or Client identifier formatted for display. Non-North American phone numbers are in [E.164](https://www.twilio.com/docs/glossary/what-e164) format (e.g., +442071838750). :ivar phone_number_sid: If the call was inbound, this is the SID of the IncomingPhoneNumber resource that received the call. If the call was outbound, it is the SID of the OutgoingCallerId resource from which the call was placed. :ivar status: - :ivar start_time: The start time of the call, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call has not yet been dialed. - :ivar end_time: The time the call ended, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call did not complete successfully. + :ivar start_time: The start time of the call, given as UTC in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call has not yet been dialed. + :ivar end_time: The time the call ended, given as UTC in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. Empty if the call did not complete successfully. :ivar duration: The length of the call in seconds. This value is empty for busy, failed, unanswered, or ongoing calls. - :ivar price: The charge for this call, in the currency associated with the account. Populated after the call is completed. May not be immediately available. + :ivar price: The charge for this call, in the currency associated with the account. Populated after the call is completed. May not be immediately available. The price associated with a call only reflects the charge for connectivity. Charges for other call-related features such as Answering Machine Detection, Text-To-Speech, and SIP REFER are not included in this value. :ivar price_unit: The currency in which `Price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g., `USD`, `EUR`, `JPY`). Always capitalized for calls. :ivar direction: A string describing the direction of the call. Can be: `inbound` for inbound calls, `outbound-api` for calls initiated via the REST API or `outbound-dial` for calls initiated by a `` verb. Using [Elastic SIP Trunking](https://www.twilio.com/docs/sip-trunking), the values can be [`trunking-terminating`](https://www.twilio.com/docs/sip-trunking#termination) for outgoing calls from your communications infrastructure to the PSTN or [`trunking-originating`](https://www.twilio.com/docs/sip-trunking#origination) for incoming calls to your communications infrastructure from the PSTN. :ivar answered_by: Either `human` or `machine` if this call was initiated with answering machine detection. Empty otherwise. @@ -131,6 +131,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[CallContext] = None @property @@ -167,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 @@ -185,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, @@ -263,19 +300,90 @@ async def update_async( time_limit=time_limit, ) - @property - def events(self) -> EventList: + 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: """ - Access the events + 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.events + 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 feedback(self) -> FeedbackList: + def events(self) -> EventList: """ - Access the feedback + Access the events """ - return self._proxy.feedback + return self._proxy.events @property def notifications(self) -> NotificationList: @@ -312,6 +420,13 @@ def streams(self) -> StreamList: """ return self._proxy.streams + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + return self._proxy.transcriptions + @property def user_defined_messages(self) -> UserDefinedMessageList: """ @@ -337,6 +452,7 @@ def __repr__(self) -> str: class CallContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the CallContext @@ -355,17 +471,31 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._uri = "/Accounts/{account_sid}/Calls/{sid}.json".format(**self._solution) self._events: Optional[EventList] = None - self._feedback: Optional[FeedbackList] = None self._notifications: Optional[NotificationList] = None self._payments: Optional[PaymentList] = None self._recordings: Optional[RecordingList] = None self._siprec: Optional[SiprecList] = None self._streams: Optional[StreamList] = None + self._transcriptions: Optional[TranscriptionList] = None self._user_defined_messages: Optional[UserDefinedMessageList] = None self._user_defined_message_subscriptions: Optional[ 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,9 +503,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -385,9 +537,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CallInstance 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) -> CallInstance: @@ -397,18 +573,45 @@ def fetch(self) -> CallInstance: :returns: The fetched CallInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return CallInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CallInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CallInstance: """ @@ -417,20 +620,31 @@ async def fetch_async(self) -> CallInstance: :returns: The fetched CallInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CallInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return CallInstance( + 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( + def _update( self, url: Union[str, object] = values.unset, method: Union[str, object] = values.unset, @@ -441,22 +655,14 @@ 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( { "Url": url, @@ -470,13 +676,54 @@ def update( "TimeLimit": time_limit, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -484,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, @@ -495,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. @@ -509,8 +756,46 @@ 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( { "Url": url, @@ -524,21 +809,108 @@ async def update_async( "TimeLimit": time_limit, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CallInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], + headers["Accept"] = "application/json" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers ) - @property + 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 @@ -551,19 +923,6 @@ def events(self) -> EventList: ) return self._events - @property - def feedback(self) -> FeedbackList: - """ - Access the feedback - """ - if self._feedback is None: - self._feedback = FeedbackList( - self._version, - self._solution["account_sid"], - self._solution["sid"], - ) - return self._feedback - @property def notifications(self) -> NotificationList: """ @@ -629,6 +988,19 @@ def streams(self) -> StreamList: ) return self._streams + @property + def transcriptions(self) -> TranscriptionList: + """ + Access the transcriptions + """ + if self._transcriptions is None: + self._transcriptions = TranscriptionList( + self._version, + self._solution["account_sid"], + self._solution["sid"], + ) + return self._transcriptions + @property def user_defined_messages(self) -> UserDefinedMessageList: """ @@ -668,12 +1040,14 @@ def __repr__(self) -> str: class CallPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CallInstance: """ Build an instance of CallInstance :param payload: Payload response from the API """ + return CallInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -688,6 +1062,7 @@ def __repr__(self) -> str: class CallList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the CallList @@ -704,9 +1079,7 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Calls.json".format(**self._solution) - self._feedback_summaries: Optional[FeedbackSummaryList] = None - - def create( + def _create( self, to: str, from_: str, @@ -722,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, @@ -740,51 +1114,18 @@ def create( 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( { "To": to, @@ -799,10 +1140,11 @@ def create( "StatusCallbackMethod": status_callback_method, "SendDigits": send_digits, "Timeout": timeout, - "Record": record, + "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, @@ -823,23 +1165,23 @@ def create( "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"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CallInstance( - self._version, payload, account_sid=self._solution["account_sid"] + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - async def create_async( + def create( self, to: str, from_: str, @@ -855,6 +1197,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, @@ -873,12 +1216,13 @@ async def create_async( 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. @@ -888,12 +1232,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). @@ -912,83 +1257,612 @@ async def create_async( :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": 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, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, + 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. + 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 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, + 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, + 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, + "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, + 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 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, + 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, + 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 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, + 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. @@ -997,12 +1871,12 @@ def stream( :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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 @@ -1013,7 +1887,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, @@ -1027,9 +1901,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, @@ -1043,23 +1917,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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 @@ -1067,10 +1939,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, @@ -1084,7 +1956,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, @@ -1110,12 +2039,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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 @@ -1125,6 +2054,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( to=to, @@ -1166,12 +2096,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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 @@ -1181,6 +2111,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1199,6 +2130,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, @@ -1223,12 +2264,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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 @@ -1253,8 +2294,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return CallPage(self._version, response, self._solution) + 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 CallPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1280,12 +2327,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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 GMT, 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 @@ -1310,10 +2357,144 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return CallPage(self._version, response, self._solution) + 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: """ @@ -1325,7 +2506,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: """ @@ -1337,18 +2518,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) - - @property - def feedback_summaries(self) -> FeedbackSummaryList: - """ - Access the feedback_summaries - """ - if self._feedback_summaries is None: - self._feedback_summaries = FeedbackSummaryList( - self._version, account_sid=self._solution["account_sid"] - ) - return self._feedback_summaries + 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 bb77d6510a..96f3eae3bf 100644 --- a/twilio/rest/api/v2010/account/call/event.py +++ b/twilio/rest/api/v2010/account/call/event.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class EventInstance(InstanceResource): - """ :ivar request: Contains a dictionary representing the request of the call. :ivar response: Contains a dictionary representing the call response, including a list of the call events. @@ -53,12 +52,14 @@ def __repr__(self) -> str: class EventPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: """ Build an instance of EventInstance :param payload: Payload response from the API """ + return EventInstance( self._version, payload, @@ -76,6 +77,7 @@ def __repr__(self) -> str: class EventList(ListResource): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ Initialize the EventList @@ -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, @@ -223,8 +327,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return EventPage(self._version, response, self._solution) + 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 EventPage(self._version, response, solution=self._solution) async def page_async( self, @@ -250,10 +360,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return EventPage(self._version, response, self._solution) + 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: """ @@ -265,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: """ @@ -277,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/feedback.py b/twilio/rest/api/v2010/account/call/feedback.py deleted file mode 100644 index 8eb84a966a..0000000000 --- a/twilio/rest/api/v2010/account/call/feedback.py +++ /dev/null @@ -1,331 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Api - 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 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 - - -class FeedbackInstance(InstanceResource): - class Issues(object): - AUDIO_LATENCY = "audio-latency" - DIGITS_NOT_CAPTURED = "digits-not-captured" - DROPPED_CALL = "dropped-call" - IMPERFECT_AUDIO = "imperfect-audio" - INCORRECT_CALLER_ID = "incorrect-caller-id" - ONE_WAY_AUDIO = "one-way-audio" - POST_DIAL_DELAY = "post-dial-delay" - UNSOLICITED_CALL = "unsolicited-call" - - """ - :ivar account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. - :ivar date_created: The date that this resource was created, given in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. - :ivar date_updated: The date that this resource was last updated, given in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. - :ivar issues: A list of issues experienced during the call. The issues can be: `imperfect-audio`, `dropped-call`, `incorrect-caller-id`, `post-dial-delay`, `digits-not-captured`, `audio-latency`, `unsolicited-call`, or `one-way-audio`. - :ivar quality_score: `1` to `5` quality score where `1` represents imperfect experience and `5` represents a perfect call. - :ivar sid: A 34 character string that uniquely identifies this resource. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], account_sid: str, call_sid: str - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - 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.issues: Optional[List["FeedbackInstance.Issues"]] = payload.get("issues") - self.quality_score: Optional[int] = deserialize.integer( - payload.get("quality_score") - ) - self.sid: Optional[str] = payload.get("sid") - - self._solution = { - "account_sid": account_sid, - "call_sid": call_sid, - } - self._context: Optional[FeedbackContext] = None - - @property - def _proxy(self) -> "FeedbackContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FeedbackContext for this FeedbackInstance - """ - if self._context is None: - self._context = FeedbackContext( - self._version, - account_sid=self._solution["account_sid"], - call_sid=self._solution["call_sid"], - ) - return self._context - - def fetch(self) -> "FeedbackInstance": - """ - Fetch the FeedbackInstance - - - :returns: The fetched FeedbackInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "FeedbackInstance": - """ - Asynchronous coroutine to fetch the FeedbackInstance - - - :returns: The fetched FeedbackInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - quality_score: Union[int, object] = values.unset, - issue: Union[List["FeedbackInstance.Issues"], object] = values.unset, - ) -> "FeedbackInstance": - """ - Update the FeedbackInstance - - :param quality_score: The call quality expressed as an integer from `1` to `5` where `1` represents very poor call quality and `5` represents a perfect call. - :param issue: One or more issues experienced during the call. The issues can be: `imperfect-audio`, `dropped-call`, `incorrect-caller-id`, `post-dial-delay`, `digits-not-captured`, `audio-latency`, `unsolicited-call`, or `one-way-audio`. - - :returns: The updated FeedbackInstance - """ - return self._proxy.update( - quality_score=quality_score, - issue=issue, - ) - - async def update_async( - self, - quality_score: Union[int, object] = values.unset, - issue: Union[List["FeedbackInstance.Issues"], object] = values.unset, - ) -> "FeedbackInstance": - """ - Asynchronous coroutine to update the FeedbackInstance - - :param quality_score: The call quality expressed as an integer from `1` to `5` where `1` represents very poor call quality and `5` represents a perfect call. - :param issue: One or more issues experienced during the call. The issues can be: `imperfect-audio`, `dropped-call`, `incorrect-caller-id`, `post-dial-delay`, `digits-not-captured`, `audio-latency`, `unsolicited-call`, or `one-way-audio`. - - :returns: The updated FeedbackInstance - """ - return await self._proxy.update_async( - quality_score=quality_score, - issue=issue, - ) - - 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 FeedbackContext(InstanceContext): - def __init__(self, version: Version, account_sid: str, call_sid: str): - """ - Initialize the FeedbackContext - - :param version: Version that contains the resource - :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. - :param call_sid: The call sid that uniquely identifies the call - """ - super().__init__(version) - - # Path Solution - self._solution = { - "account_sid": account_sid, - "call_sid": call_sid, - } - self._uri = "/Accounts/{account_sid}/Calls/{call_sid}/Feedback.json".format( - **self._solution - ) - - def fetch(self) -> FeedbackInstance: - """ - Fetch the FeedbackInstance - - - :returns: The fetched FeedbackInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - call_sid=self._solution["call_sid"], - ) - - async def fetch_async(self) -> FeedbackInstance: - """ - Asynchronous coroutine to fetch the FeedbackInstance - - - :returns: The fetched FeedbackInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - call_sid=self._solution["call_sid"], - ) - - def update( - self, - quality_score: Union[int, object] = values.unset, - issue: Union[List["FeedbackInstance.Issues"], object] = values.unset, - ) -> FeedbackInstance: - """ - Update the FeedbackInstance - - :param quality_score: The call quality expressed as an integer from `1` to `5` where `1` represents very poor call quality and `5` represents a perfect call. - :param issue: One or more issues experienced during the call. The issues can be: `imperfect-audio`, `dropped-call`, `incorrect-caller-id`, `post-dial-delay`, `digits-not-captured`, `audio-latency`, `unsolicited-call`, or `one-way-audio`. - - :returns: The updated FeedbackInstance - """ - data = values.of( - { - "QualityScore": quality_score, - "Issue": serialize.map(issue, lambda e: e), - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - call_sid=self._solution["call_sid"], - ) - - async def update_async( - self, - quality_score: Union[int, object] = values.unset, - issue: Union[List["FeedbackInstance.Issues"], object] = values.unset, - ) -> FeedbackInstance: - """ - Asynchronous coroutine to update the FeedbackInstance - - :param quality_score: The call quality expressed as an integer from `1` to `5` where `1` represents very poor call quality and `5` represents a perfect call. - :param issue: One or more issues experienced during the call. The issues can be: `imperfect-audio`, `dropped-call`, `incorrect-caller-id`, `post-dial-delay`, `digits-not-captured`, `audio-latency`, `unsolicited-call`, or `one-way-audio`. - - :returns: The updated FeedbackInstance - """ - data = values.of( - { - "QualityScore": quality_score, - "Issue": serialize.map(issue, lambda e: e), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FeedbackInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - call_sid=self._solution["call_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 FeedbackList(ListResource): - def __init__(self, version: Version, account_sid: str, call_sid: str): - """ - Initialize the FeedbackList - - :param version: Version that contains the resource - :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. - :param call_sid: The call sid that uniquely identifies the call - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "account_sid": account_sid, - "call_sid": call_sid, - } - - def get(self) -> FeedbackContext: - """ - Constructs a FeedbackContext - - """ - return FeedbackContext( - self._version, - account_sid=self._solution["account_sid"], - call_sid=self._solution["call_sid"], - ) - - def __call__(self) -> FeedbackContext: - """ - Constructs a FeedbackContext - - """ - return FeedbackContext( - self._version, - account_sid=self._solution["account_sid"], - call_sid=self._solution["call_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/api/v2010/account/call/feedback_summary.py b/twilio/rest/api/v2010/account/call/feedback_summary.py deleted file mode 100644 index fcfb4e0ab1..0000000000 --- a/twilio/rest/api/v2010/account/call/feedback_summary.py +++ /dev/null @@ -1,374 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Api - 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 date, datetime -from typing import Any, Dict, List, Optional, Union -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 - - -class FeedbackSummaryInstance(InstanceResource): - class Status(object): - QUEUED = "queued" - IN_PROGRESS = "in-progress" - COMPLETED = "completed" - FAILED = "failed" - - """ - :ivar account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. - :ivar call_count: The total number of calls. - :ivar call_feedback_count: The total number of calls with a feedback entry. - :ivar date_created: The date that this resource was created, given in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. - :ivar date_updated: The date that this resource was last updated, given in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. - :ivar end_date: The last date for which feedback entries are included in this Feedback Summary, formatted as `YYYY-MM-DD` and specified in UTC. - :ivar include_subaccounts: Whether the feedback summary includes subaccounts; `true` if it does, otherwise `false`. - :ivar issues: A list of issues experienced during the call. The issues can be: `imperfect-audio`, `dropped-call`, `incorrect-caller-id`, `post-dial-delay`, `digits-not-captured`, `audio-latency`, or `one-way-audio`. - :ivar quality_score_average: The average QualityScore of the feedback entries. - :ivar quality_score_median: The median QualityScore of the feedback entries. - :ivar quality_score_standard_deviation: The standard deviation of the quality scores. - :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar start_date: The first date for which feedback entries are included in this feedback summary, formatted as `YYYY-MM-DD` and specified in UTC. - :ivar status: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - account_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.call_count: Optional[int] = deserialize.integer(payload.get("call_count")) - self.call_feedback_count: Optional[int] = deserialize.integer( - payload.get("call_feedback_count") - ) - 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.end_date: Optional[date] = deserialize.iso8601_date( - payload.get("end_date") - ) - self.include_subaccounts: Optional[bool] = payload.get("include_subaccounts") - self.issues: Optional[List[object]] = payload.get("issues") - self.quality_score_average: Optional[float] = deserialize.decimal( - payload.get("quality_score_average") - ) - self.quality_score_median: Optional[float] = deserialize.decimal( - payload.get("quality_score_median") - ) - self.quality_score_standard_deviation: Optional[float] = deserialize.decimal( - payload.get("quality_score_standard_deviation") - ) - self.sid: Optional[str] = payload.get("sid") - self.start_date: Optional[date] = deserialize.iso8601_date( - payload.get("start_date") - ) - self.status: Optional["FeedbackSummaryInstance.Status"] = payload.get("status") - - self._solution = { - "account_sid": account_sid, - "sid": sid or self.sid, - } - self._context: Optional[FeedbackSummaryContext] = None - - @property - def _proxy(self) -> "FeedbackSummaryContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FeedbackSummaryContext for this FeedbackSummaryInstance - """ - if self._context is None: - self._context = FeedbackSummaryContext( - self._version, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the FeedbackSummaryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FeedbackSummaryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "FeedbackSummaryInstance": - """ - Fetch the FeedbackSummaryInstance - - - :returns: The fetched FeedbackSummaryInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "FeedbackSummaryInstance": - """ - Asynchronous coroutine to fetch the FeedbackSummaryInstance - - - :returns: The fetched FeedbackSummaryInstance - """ - 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 "".format(context) - - -class FeedbackSummaryContext(InstanceContext): - def __init__(self, version: Version, account_sid: str, sid: str): - """ - Initialize the FeedbackSummaryContext - - :param version: Version that contains the resource - :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. - :param sid: A 34 character string that uniquely identifies this resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "account_sid": account_sid, - "sid": sid, - } - self._uri = "/Accounts/{account_sid}/Calls/FeedbackSummary/{sid}.json".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the FeedbackSummaryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FeedbackSummaryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> FeedbackSummaryInstance: - """ - Fetch the FeedbackSummaryInstance - - - :returns: The fetched FeedbackSummaryInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return FeedbackSummaryInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> FeedbackSummaryInstance: - """ - Asynchronous coroutine to fetch the FeedbackSummaryInstance - - - :returns: The fetched FeedbackSummaryInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return FeedbackSummaryInstance( - self._version, - payload, - account_sid=self._solution["account_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 "".format(context) - - -class FeedbackSummaryList(ListResource): - def __init__(self, version: Version, account_sid: str): - """ - Initialize the FeedbackSummaryList - - :param version: Version that contains the resource - :param account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this resource. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "account_sid": account_sid, - } - self._uri = "/Accounts/{account_sid}/Calls/FeedbackSummary.json".format( - **self._solution - ) - - def create( - self, - start_date: date, - end_date: date, - include_subaccounts: Union[bool, object] = values.unset, - status_callback: Union[str, object] = values.unset, - status_callback_method: Union[str, object] = values.unset, - ) -> FeedbackSummaryInstance: - """ - Create the FeedbackSummaryInstance - - :param start_date: Only include feedback given on or after this date. Format is `YYYY-MM-DD` and specified in UTC. - :param end_date: Only include feedback given on or before this date. Format is `YYYY-MM-DD` and specified in UTC. - :param include_subaccounts: Whether to also include Feedback resources from all subaccounts. `true` includes feedback from all subaccounts and `false`, the default, includes feedback from only the specified account. - :param status_callback: The URL that we will request when the feedback summary is complete. - :param status_callback_method: The HTTP method (`GET` or `POST`) we use to make the request to the `StatusCallback` URL. - - :returns: The created FeedbackSummaryInstance - """ - data = values.of( - { - "StartDate": serialize.iso8601_date(start_date), - "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return FeedbackSummaryInstance( - self._version, payload, account_sid=self._solution["account_sid"] - ) - - async def create_async( - self, - start_date: date, - end_date: date, - include_subaccounts: Union[bool, object] = values.unset, - status_callback: Union[str, object] = values.unset, - status_callback_method: Union[str, object] = values.unset, - ) -> FeedbackSummaryInstance: - """ - Asynchronously create the FeedbackSummaryInstance - - :param start_date: Only include feedback given on or after this date. Format is `YYYY-MM-DD` and specified in UTC. - :param end_date: Only include feedback given on or before this date. Format is `YYYY-MM-DD` and specified in UTC. - :param include_subaccounts: Whether to also include Feedback resources from all subaccounts. `true` includes feedback from all subaccounts and `false`, the default, includes feedback from only the specified account. - :param status_callback: The URL that we will request when the feedback summary is complete. - :param status_callback_method: The HTTP method (`GET` or `POST`) we use to make the request to the `StatusCallback` URL. - - :returns: The created FeedbackSummaryInstance - """ - data = values.of( - { - "StartDate": serialize.iso8601_date(start_date), - "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FeedbackSummaryInstance( - self._version, payload, account_sid=self._solution["account_sid"] - ) - - def get(self, sid: str) -> FeedbackSummaryContext: - """ - Constructs a FeedbackSummaryContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return FeedbackSummaryContext( - self._version, account_sid=self._solution["account_sid"], sid=sid - ) - - def __call__(self, sid: str) -> FeedbackSummaryContext: - """ - Constructs a FeedbackSummaryContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return FeedbackSummaryContext( - self._version, account_sid=self._solution["account_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/api/v2010/account/call/notification.py b/twilio/rest/api/v2010/account/call/notification.py index 5db223c859..bed0f202c0 100644 --- a/twilio/rest/api/v2010/account/call/notification.py +++ b/twilio/rest/api/v2010/account/call/notification.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,7 +24,6 @@ class NotificationInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Call Notification resource. :ivar api_version: The API version used to create the Call Notification resource. @@ -84,6 +83,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[NotificationContext] = None @property @@ -121,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 @@ -132,6 +150,7 @@ def __repr__(self) -> str: class NotificationContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): """ Initialize the NotificationContext @@ -155,6 +174,22 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): ) ) + 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) -> NotificationInstance: """ Fetch the NotificationInstance @@ -162,19 +197,47 @@ def fetch(self) -> NotificationInstance: :returns: The fetched NotificationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], ) - return NotificationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> NotificationInstance: """ @@ -183,19 +246,31 @@ async def fetch_async(self) -> NotificationInstance: :returns: The fetched NotificationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], ) - return NotificationInstance( + 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: """ @@ -208,12 +283,14 @@ def __repr__(self) -> str: class NotificationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: """ Build an instance of NotificationInstance :param payload: Payload response from the API """ + return NotificationInstance( self._version, payload, @@ -231,6 +308,7 @@ def __repr__(self) -> str: class NotificationList(ListResource): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ Initialize the NotificationList @@ -331,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, @@ -358,6 +512,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( log=log, @@ -396,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( @@ -408,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, @@ -444,8 +674,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return NotificationPage(self._version, response, self._solution) + 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 NotificationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -483,10 +719,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return NotificationPage(self._version, response, self._solution) + 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: """ @@ -498,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: """ @@ -510,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 10d00441ba..1d203e8521 100644 --- a/twilio/rest/api/v2010/account/call/payment.py +++ b/twilio/rest/api/v2010/account/call/payment.py @@ -12,10 +12,10 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,6 +23,7 @@ class PaymentInstance(InstanceResource): + class BankAccountType(object): CONSUMER_CHECKING = "consumer-checking" CONSUMER_SAVINGS = "consumer-savings" @@ -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" @@ -47,6 +52,7 @@ class Status(object): class TokenType(object): ONE_TIME = "one-time" REUSABLE = "reusable" + PAYMENT_METHOD = "payment-method" """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Payments resource. @@ -83,6 +89,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[PaymentContext] = None @property @@ -150,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 @@ -161,6 +216,7 @@ def __repr__(self) -> str: class PaymentContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): """ Initialize the PaymentContext @@ -184,23 +240,20 @@ 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 - - :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: + Internal helper for update operation - :returns: The updated PaymentInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "IdempotencyKey": idempotency_key, @@ -209,13 +262,39 @@ def update( "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -224,23 +303,52 @@ 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( { "IdempotencyKey": idempotency_key, @@ -249,13 +357,39 @@ async def update_async( "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -264,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 @@ -275,6 +441,7 @@ def __repr__(self) -> str: class PaymentList(ListResource): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ Initialize the PaymentList @@ -295,6 +462,68 @@ def __init__(self, version: Version, account_sid: str, call_sid: str): **self._solution ) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "IdempotencyKey": idempotency_key, + "StatusCallback": status_callback, + "BankAccountType": bank_account_type, + "ChargeAmount": charge_amount, + "Currency": currency, + "Description": description, + "Input": input, + "MinPostalCodeLength": min_postal_code_length, + "Parameter": serialize.object(parameter), + "PaymentConnector": payment_connector, + "PaymentMethod": payment_method, + "PostalCode": serialize.boolean_to_string(postal_code), + "SecurityCode": serialize.boolean_to_string(security_code), + "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"}) + + 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, idempotency_key: str, @@ -315,6 +544,8 @@ def create( 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 @@ -335,36 +566,31 @@ def create( :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 """ - data = values.of( - { - "IdempotencyKey": idempotency_key, - "StatusCallback": status_callback, - "BankAccountType": bank_account_type, - "ChargeAmount": charge_amount, - "Currency": currency, - "Description": description, - "Input": input, - "MinPostalCodeLength": min_postal_code_length, - "Parameter": serialize.object(parameter), - "PaymentConnector": payment_connector, - "PaymentMethod": payment_method, - "PostalCode": postal_code, - "SecurityCode": security_code, - "Timeout": timeout, - "TokenType": token_type, - "ValidCardTypes": valid_card_types, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, @@ -372,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, @@ -392,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) @@ -412,9 +640,69 @@ 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( { "IdempotencyKey": idempotency_key, @@ -428,20 +716,92 @@ async def create_async( "Parameter": serialize.object(parameter), "PaymentConnector": payment_connector, "PaymentMethod": payment_method, - "PostalCode": postal_code, - "SecurityCode": security_code, + "PostalCode": serialize.boolean_to_string(postal_code), + "SecurityCode": serialize.boolean_to_string(security_code), "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"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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: 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, @@ -449,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 7ca36f3e00..1e17481856 100644 --- a/twilio/rest/api/v2010/account/call/recording.py +++ b/twilio/rest/api/v2010/account/call/recording.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,6 +24,7 @@ class RecordingInstance(InstanceResource): + class Source(object): DIALVERB = "DialVerb" CONFERENCE = "Conference" @@ -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 @@ -206,6 +280,7 @@ def __repr__(self) -> str: class RecordingContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): """ Initialize the RecordingContext @@ -229,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 @@ -236,9 +325,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -248,9 +359,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -260,19 +395,47 @@ def fetch(self) -> RecordingInstance: :returns: The fetched RecordingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], ) - return RecordingInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RecordingInstance: """ @@ -281,46 +444,74 @@ async def fetch_async(self) -> RecordingInstance: :returns: The fetched RecordingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], ) - return RecordingInstance( + 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( + 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( { "Status": status, "PauseBehavior": pause_behavior, } ) + 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, + 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, @@ -329,32 +520,75 @@ 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( { "Status": status, "PauseBehavior": pause_behavior, } ) + 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, + 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, @@ -363,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 @@ -374,12 +633,14 @@ def __repr__(self) -> str: class RecordingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: """ Build an instance of RecordingInstance :param payload: Payload response from the API """ + return RecordingInstance( self._version, payload, @@ -397,6 +658,7 @@ def __repr__(self) -> str: class RecordingList(ListResource): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ Initialize the RecordingList @@ -417,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, @@ -425,19 +687,15 @@ 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 - - :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. + Internal helper for create operation - :returns: The created RecordingInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "RecordingStatusCallbackEvent": serialize.map( @@ -448,15 +706,51 @@ def create( "Trim": trim, "RecordingChannels": recording_channels, "RecordingTrack": recording_track, + "RecordingConfigurationId": recording_configuration_id, } ) + 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, + 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, @@ -464,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, @@ -472,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). @@ -482,9 +777,44 @@ 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( { "RecordingStatusCallbackEvent": serialize.map( @@ -495,15 +825,51 @@ 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"}) + + 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, + 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, @@ -511,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, @@ -583,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, @@ -608,6 +1084,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -643,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( @@ -654,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, @@ -687,8 +1233,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RecordingPage(self._version, response, self._solution) + 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 RecordingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -723,10 +1275,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RecordingPage(self._version, response, self._solution) + 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: """ @@ -738,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: """ @@ -750,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 86bfd5c6bc..30ffea6d94 100644 --- a/twilio/rest/api/v2010/account/call/siprec.py +++ b/twilio/rest/api/v2010/account/call/siprec.py @@ -12,10 +12,10 @@ 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 @@ -23,6 +23,7 @@ class SiprecInstance(InstanceResource): + class Status(object): IN_PROGRESS = "in-progress" STOPPED = "stopped" @@ -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 @@ -126,6 +156,7 @@ def __repr__(self) -> str: class SiprecContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): """ Initialize the SiprecContext @@ -147,26 +178,38 @@ 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 + Internal helper for update operation - :param status: - - :returns: The updated SiprecInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Status": status, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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: "SiprecInstance.UpdateStatus") -> SiprecInstance: + """ + Update the SiprecInstance + + :param status: + + :returns: The updated SiprecInstance + """ + payload, _, _ = self._update(status=status) return SiprecInstance( self._version, payload, @@ -175,28 +218,60 @@ 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( { "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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: "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, @@ -205,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 @@ -216,6 +311,7 @@ def __repr__(self) -> str: class SiprecList(ListResource): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ Initialize the SiprecList @@ -236,7 +332,7 @@ 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, @@ -441,216 +537,14 @@ def create( parameter98_value: Union[str, object] = values.unset, parameter99_name: Union[str, object] = values.unset, parameter99_value: Union[str, object] = values.unset, - ) -> SiprecInstance: + ) -> tuple: """ - Create the SiprecInstance + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Name": name, @@ -858,13 +752,2321 @@ def create( "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, + 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: + """ + 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. + :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 - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + :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, @@ -872,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, @@ -1077,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. @@ -1285,228 +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, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 1999e9379b..99338e0663 100644 --- a/twilio/rest/api/v2010/account/call/stream.py +++ b/twilio/rest/api/v2010/account/call/stream.py @@ -12,10 +12,10 @@ 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 @@ -23,6 +23,7 @@ class StreamInstance(InstanceResource): + class Status(object): IN_PROGRESS = "in-progress" STOPPED = "stopped" @@ -39,7 +40,7 @@ class UpdateStatus(object): :ivar sid: The SID of the Stream resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Stream resource. :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Stream resource is associated with. - :ivar name: The user-specified name of this Stream, if one was given when the Stream was created. This may be used to stop the Stream. + :ivar 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. :ivar status: :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. @@ -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 @@ -126,6 +156,7 @@ def __repr__(self) -> str: class StreamContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): """ Initialize the StreamContext @@ -133,7 +164,7 @@ def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): :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 this Stream resource. :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Stream resource is associated with. - :param sid: The SID of the Stream resource, or the `name` used when creating the resource + :param sid: The SID or the `name` of the Stream resource to be stopped """ super().__init__(version) @@ -149,26 +180,38 @@ 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 + Internal helper for update operation - :param status: - - :returns: The updated StreamInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Status": status, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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: "StreamInstance.UpdateStatus") -> StreamInstance: + """ + Update the StreamInstance + + :param status: + + :returns: The updated StreamInstance + """ + payload, _, _ = self._update(status=status) return StreamInstance( self._version, payload, @@ -177,28 +220,60 @@ 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( { "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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: "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, @@ -207,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 @@ -218,6 +313,7 @@ def __repr__(self) -> str: class StreamList(ListResource): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ Initialize the StreamList @@ -238,7 +334,7 @@ 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, @@ -443,216 +539,14 @@ def create( parameter98_value: Union[str, object] = values.unset, parameter99_name: Union[str, object] = values.unset, parameter99_value: Union[str, object] = values.unset, - ) -> StreamInstance: + ) -> tuple: """ - Create the StreamInstance + Internal helper for create operation - :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 may be used to stop the Stream. - :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 StreamInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Url": url, @@ -860,13 +754,2321 @@ def create( "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, + 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: + """ + 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. + :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 - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + :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, @@ -874,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, @@ -1079,15 +3281,15 @@ 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 may be used to stop the Stream. + :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 of the status callback. - :param status_callback_method: The http method for the status_callback (one of GET, POST). + :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 @@ -1287,234 +3489,226 @@ 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, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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: """ Constructs a StreamContext - :param sid: The SID of the Stream resource, or the `name` used when creating the resource + :param sid: The SID or the `name` of the Stream resource to be stopped """ return StreamContext( self._version, @@ -1527,7 +3721,7 @@ def __call__(self, sid: str) -> StreamContext: """ Constructs a StreamContext - :param sid: The SID of the Stream resource, or the `name` used when creating the resource + :param sid: The SID or the `name` of the Stream resource to be stopped """ return StreamContext( self._version, diff --git a/twilio/rest/api/v2010/account/call/transcription.py b/twilio/rest/api/v2010/account/call/transcription.py new file mode 100644 index 0000000000..0d56c61ff3 --- /dev/null +++ b/twilio/rest/api/v2010/account/call/transcription.py @@ -0,0 +1,791 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + 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_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 Status(object): + IN_PROGRESS = "in-progress" + STOPPED = "stopped" + + class Track(object): + INBOUND_TRACK = "inbound_track" + OUTBOUND_TRACK = "outbound_track" + BOTH_TRACKS = "both_tracks" + + class UpdateStatus(object): + STOPPED = "stopped" + + """ + :ivar sid: The SID of the Transcription resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Transcription resource. + :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + :ivar 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. + :ivar status: + :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar uri: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + call_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.call_sid: Optional[str] = payload.get("call_sid") + self.name: Optional[str] = payload.get("name") + self.status: Optional["TranscriptionInstance.Status"] = payload.get("status") + self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( + payload.get("date_updated") + ) + self.uri: Optional[str] = payload.get("uri") + + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid or self.sid, + } + + 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, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + return self._context + + def update( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> "TranscriptionInstance": + """ + Update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + return self._proxy.update( + status=status, + ) + + async def update_async( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> "TranscriptionInstance": + """ + Asynchronous coroutine to update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + return await self._proxy.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionContext(InstanceContext): + + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): + """ + Initialize the TranscriptionContext + + :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 this Transcription resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + :param sid: The SID of the Transcription resource, or the `name` used when creating the resource + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + "sid": sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Transcriptions/{sid}.json".format( + **self._solution + ) + ) + + def _update(self, status: "TranscriptionInstance.UpdateStatus") -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + } + ) + 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: "TranscriptionInstance.UpdateStatus" + ) -> TranscriptionInstance: + """ + Update the TranscriptionInstance + + :param status: + + :returns: The updated TranscriptionInstance + """ + payload, _, _ = self._update(status=status) + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, status: "TranscriptionInstance.UpdateStatus" + ) -> ApiResponse: + """ + Update the TranscriptionInstance and return response metadata + + :param status: + + :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( + { + "Status": status, + } + ) + 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: "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, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class TranscriptionList(ListResource): + + def __init__(self, version: Version, account_sid: str, call_sid: str): + """ + Initialize the TranscriptionList + + :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 this Transcription resource. + :param call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Transcription resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "call_sid": call_sid, + } + self._uri = ( + "/Accounts/{account_sid}/Calls/{call_sid}/Transcriptions.json".format( + **self._solution + ) + ) + + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Name": name, + "Track": track, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "InboundTrackLabel": inbound_track_label, + "OutboundTrackLabel": outbound_track_label, + "PartialResults": serialize.boolean_to_string(partial_results), + "LanguageCode": language_code, + "TranscriptionEngine": transcription_engine, + "ProfanityFilter": serialize.boolean_to_string(profanity_filter), + "SpeechModel": speech_model, + "Hints": hints, + "EnableAutomaticPunctuation": serialize.boolean_to_string( + 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"}) + + 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, + 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, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + ) + + def create_with_http_info( + 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: + """ + 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 = 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( + { + "Name": name, + "Track": track, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "InboundTrackLabel": inbound_track_label, + "OutboundTrackLabel": outbound_track_label, + "PartialResults": serialize.boolean_to_string(partial_results), + "LanguageCode": language_code, + "TranscriptionEngine": transcription_engine, + "ProfanityFilter": serialize.boolean_to_string(profanity_filter), + "SpeechModel": speech_model, + "Hints": hints, + "EnableAutomaticPunctuation": serialize.boolean_to_string( + 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"}) + + 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, + 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, + account_sid=self._solution["account_sid"], + 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 + + :param sid: The SID of the Transcription resource, or the `name` used when creating the resource + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> TranscriptionContext: + """ + Constructs a TranscriptionContext + + :param sid: The SID of the Transcription resource, or the `name` used when creating the resource + """ + return TranscriptionContext( + self._version, + account_sid=self._solution["account_sid"], + call_sid=self._solution["call_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" 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 0beef389d7..d1ed0a91ee 100644 --- a/twilio/rest/api/v2010/account/call/user_defined_message.py +++ b/twilio/rest/api/v2010/account/call/user_defined_message.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class UserDefinedMessageInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created User Defined Message. :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message is associated with. @@ -59,6 +58,7 @@ def __repr__(self) -> str: class UserDefinedMessageList(ListResource): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ Initialize the UserDefinedMessageList @@ -81,30 +81,44 @@ 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( { "Content": content, "IdempotencyKey": idempotency_key, } ) + 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, + 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, @@ -112,30 +126,68 @@ 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( { "Content": content, "IdempotencyKey": idempotency_key, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -143,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 c34905dcdb..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 @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class UserDefinedMessageSubscriptionInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that subscribed to the User Defined Messages. :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the User Defined Message Subscription is associated with. This refers to the Call SID that is producing the User Defined Messages. @@ -55,6 +54,7 @@ def __init__( "call_sid": call_sid, "sid": sid or self.sid, } + self._context: Optional[UserDefinedMessageSubscriptionContext] = None @property @@ -92,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 @@ -105,6 +123,7 @@ def __repr__(self) -> str: class UserDefinedMessageSubscriptionContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, call_sid: str, sid: str): """ Initialize the UserDefinedMessageSubscriptionContext @@ -126,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 @@ -133,9 +166,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -145,10 +200,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserDefinedMessageSubscriptionInstance 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 __repr__(self) -> str: """ @@ -163,6 +226,7 @@ def __repr__(self) -> str: class UserDefinedMessageSubscriptionList(ListResource): + def __init__(self, version: Version, account_sid: str, call_sid: str): """ Initialize the UserDefinedMessageSubscriptionList @@ -183,21 +247,19 @@ 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( { "Callback": callback, @@ -205,13 +267,34 @@ def create( "Method": method, } ) + 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, + 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, @@ -219,21 +302,45 @@ 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( { "Callback": callback, @@ -241,13 +348,34 @@ async def create_async( "Method": method, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -255,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 062c7013ed..9edc8ce213 100644 --- a/twilio/rest/api/v2010/account/conference/__init__.py +++ b/twilio/rest/api/v2010/account/conference/__init__.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -26,6 +26,7 @@ class ConferenceInstance(InstanceResource): + class ReasonConferenceEnded(object): CONFERENCE_ENDED_VIA_API = "conference-ended-via-api" PARTICIPANT_WITH_END_CONFERENCE_ON_EXIT_LEFT = ( @@ -47,12 +48,12 @@ class UpdateStatus(object): """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Conference resource. - :ivar date_created: The date and time in GMT that this 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 this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_created: The date and time in UTC that this resource was created specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :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. Maxiumum 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 sid: The unique string that that we created to identify this Conference resource. + :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`, `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`. :ivar subresource_uris: A list of related resources identified by their URIs 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: """ @@ -199,6 +261,7 @@ def __repr__(self) -> str: class ConferenceContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the ConferenceContext @@ -221,6 +284,22 @@ def __init__(self, version: Version, account_sid: str, sid: str): self._participants: Optional[ParticipantList] = None self._recordings: Optional[RecordingList] = None + 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) -> ConferenceInstance: """ Fetch the ConferenceInstance @@ -228,18 +307,45 @@ def fetch(self) -> ConferenceInstance: :returns: The fetched ConferenceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return ConferenceInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConferenceInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ConferenceInstance: """ @@ -248,34 +354,43 @@ async def fetch_async(self) -> ConferenceInstance: :returns: The fetched ConferenceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ConferenceInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return ConferenceInstance( + 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( + 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( { "Status": status, @@ -283,13 +398,34 @@ def update( "AnnounceMethod": announce_method, } ) + 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, + 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, @@ -297,21 +433,45 @@ 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( { "Status": status, @@ -319,13 +479,34 @@ async def update_async( "AnnounceMethod": announce_method, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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["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, @@ -333,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: """ @@ -370,12 +577,14 @@ def __repr__(self) -> str: class ConferencePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: """ Build an instance of ConferenceInstance :param payload: Payload response from the API """ + return ConferenceInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -390,6 +599,7 @@ def __repr__(self) -> str: class ConferenceList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the ConferenceList @@ -425,12 +635,12 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_updated: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date date_updated_before: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date date_updated_after: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. + :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() @@ -476,12 +686,12 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_updated: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date date_updated_before: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date date_updated_after: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. + :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() @@ -508,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, @@ -526,12 +836,12 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_updated: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date date_updated_before: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date date_updated_after: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. + :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 @@ -543,6 +853,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -576,12 +887,12 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param date date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date date_updated: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date date_updated_before: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date date_updated_after: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. + :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 @@ -593,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( @@ -609,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, @@ -627,12 +1037,12 @@ def page( Retrieve a single page of ConferenceInstance records from the API. Request is executed immediately - :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date_updated: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date_updated_before: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date_updated_after: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. + :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 @@ -657,8 +1067,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ConferencePage(self._version, response, self._solution) + 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 ConferencePage(self._version, response, solution=self._solution) async def page_async( self, @@ -678,12 +1094,12 @@ async def page_async( Asynchronously retrieve a single page of ConferenceInstance records from the API. Request is executed immediately - :param date_created: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date_created_before: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date_created_after: The `date_created` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that started on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that started on or after midnight on a date, use `>=YYYY-MM-DD`. - :param date_updated: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date_updated_before: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. - :param date_updated_after: The `date_updated` value, specified as `YYYY-MM-DD`, of the resources to read. To read conferences that were last updated on or before midnight on a date, use `<=YYYY-MM-DD`, and to specify conferences that were last updated on or after midnight on a given date, use `>=YYYY-MM-DD`. + :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 @@ -708,10 +1124,132 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ConferencePage(self._version, response, self._solution) + 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: """ @@ -723,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: """ @@ -735,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 c4eee73400..616cad578a 100644 --- a/twilio/rest/api/v2010/account/conference/participant.py +++ b/twilio/rest/api/v2010/account/conference/participant.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class ParticipantInstance(InstanceResource): + class Status(object): QUEUED = "queued" CONNECTING = "connecting" @@ -46,6 +47,7 @@ class Status(object): :ivar hold: Whether the participant is on hold. Can be `true` or `false`. :ivar start_conference_on_enter: Whether the conference starts when the participant joins the conference, 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. :ivar status: + :ivar queue_time: The wait time in milliseconds before participant's call is placed. Only available in the response to a create participant request. :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. """ @@ -80,6 +82,7 @@ def __init__( "start_conference_on_enter" ) self.status: Optional["ParticipantInstance.Status"] = payload.get("status") + self.queue_time: Optional[str] = payload.get("queue_time") self.uri: Optional[str] = payload.get("uri") self._solution = { @@ -87,6 +90,7 @@ def __init__( "conference_sid": conference_sid, "call_sid": call_sid or self.call_sid, } + self._context: Optional[ParticipantContext] = None @property @@ -124,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 @@ -142,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, @@ -166,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`. @@ -214,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`. @@ -238,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 @@ -249,6 +385,7 @@ def __repr__(self) -> str: class ParticipantContext(InstanceContext): + def __init__( self, version: Version, account_sid: str, conference_sid: str, call_sid: str ): @@ -272,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 @@ -279,9 +430,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -291,9 +464,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance 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) -> ParticipantInstance: @@ -303,19 +500,47 @@ def fetch(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], ) - return ParticipantInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ParticipantInstance: """ @@ -324,21 +549,33 @@ async def fetch_async(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + call_sid=self._solution["call_sid"], ) - return ParticipantInstance( + 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( + def _update( self, muted: Union[bool, object] = values.unset, hold: Union[bool, object] = values.unset, @@ -352,57 +589,43 @@ 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 - - :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`. + Internal helper for update operation - :returns: The updated ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { - "Muted": muted, - "Hold": hold, + "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": beep_on_exit, - "EndConferenceOnExit": end_conference_on_exit, - "Coaching": coaching, + "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({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ParticipantInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - conference_sid=self._solution["conference_sid"], - call_sid=self._solution["call_sid"], + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - async def update_async( + def update( self, muted: Union[bool, object] = values.unset, hold: Union[bool, object] = values.unset, @@ -418,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. @@ -426,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`. @@ -435,29 +658,20 @@ async def update_async( :returns: The updated ParticipantInstance """ - data = values.of( - { - "Muted": muted, - "Hold": hold, - "HoldUrl": hold_url, - "HoldMethod": hold_method, - "AnnounceUrl": announce_url, - "AnnounceMethod": announce_method, - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "BeepOnExit": beep_on_exit, - "EndConferenceOnExit": end_conference_on_exit, - "Coaching": coaching, - "CallSidToCoach": call_sid_to_coach, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, @@ -466,23 +680,586 @@ async def update_async( call_sid=self._solution["call_sid"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation + 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: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + 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 = 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) class ParticipantPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: """ - Build an instance of ParticipantInstance + Build an instance of ParticipantInstance + + :param payload: Payload response from the API + """ + + return ParticipantInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + def __init__(self, version: Version, account_sid: str, conference_sid: str): + """ + Initialize the ParticipantList + + :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 Participant resources to read. + :param conference_sid: The SID of the conference with the participants to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "conference_sid": conference_sid, + } + self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Participants.json".format( + **self._solution + ) + + def _create( + 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal 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), + "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, + "ConferenceRecord": conference_record, + "ConferenceTrim": conference_trim, + "ConferenceStatusCallback": conference_status_callback, + "ConferenceStatusCallbackMethod": conference_status_callback_method, + "ConferenceStatusCallbackEvent": serialize.map( + conference_status_callback_event, lambda e: e + ), + "RecordingChannels": recording_channels, + "RecordingStatusCallback": recording_status_callback, + "RecordingStatusCallbackMethod": recording_status_callback_method, + "SipAuthUsername": sip_auth_username, + "SipAuthPassword": sip_auth_password, + "Region": region, + "ConferenceRecordingStatusCallback": conference_recording_status_callback, + "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, + "RecordingStatusCallbackEvent": serialize.map( + recording_status_callback_event, lambda e: e + ), + "ConferenceRecordingStatusCallbackEvent": serialize.map( + conference_recording_status_callback_event, lambda e: e + ), + "Coaching": serialize.boolean_to_string(coaching), + "CallSidToCoach": call_sid_to_coach, + "JitterBufferSize": jitter_buffer_size, + "Byoc": byoc, + "CallerId": caller_id, + "CallReason": call_reason, + "RecordingTrack": recording_track, + "RecordingConfigurationId": recording_configuration_id, + "TimeLimit": time_limit, + "MachineDetection": machine_detection, + "MachineDetectionTimeout": machine_detection_timeout, + "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, + "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, + "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, + "AmdStatusCallback": amd_status_callback, + "AmdStatusCallbackMethod": amd_status_callback_method, + "Trim": trim, + "CallToken": call_token, + "ClientNotificationUrl": client_notification_url, + "CallerDisplayName": caller_display_name, + } + ) + 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, + 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> ParticipantInstance: + """ + Create the ParticipantInstance - :param payload: Payload response from the API + :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 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. + + :returns: The created ParticipantInstance """ + 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, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + ) return ParticipantInstance( self._version, payload, @@ -490,37 +1267,7 @@ def get_instance(self, payload: Dict[str, Any]) -> ParticipantInstance: conference_sid=self._solution["conference_sid"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class ParticipantList(ListResource): - def __init__(self, version: Version, account_sid: str, conference_sid: str): - """ - Initialize the ParticipantList - - :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 Participant resources to read. - :param conference_sid: The SID of the conference with the participants to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "account_sid": account_sid, - "conference_sid": conference_sid, - } - self._uri = "/Accounts/{account_sid}/Conferences/{conference_sid}/Participants.json".format( - **self._solution - ) - - def create( + def create_with_http_info( self, from_: str, to: str, @@ -562,6 +1309,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, @@ -570,12 +1318,16 @@ def create( 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, - ) -> ParticipantInstance: + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Create the ParticipantInstance + 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, 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`. @@ -586,12 +1338,12 @@ def create( :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`. :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 your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :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`. @@ -600,7 +1352,7 @@ def create( :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'`. @@ -612,17 +1364,146 @@ def create( :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. 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: 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 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. + + :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, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, + ) + 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) - :returns: The created ParticipantInstance + 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "From": from_, @@ -634,14 +1515,18 @@ def create( ), "Label": label, "Timeout": timeout, - "Record": record, - "Muted": muted, + "Record": serialize.boolean_to_string(record), + "Muted": serialize.boolean_to_string(muted), "Beep": beep, - "StartConferenceOnEnter": start_conference_on_enter, - "EndConferenceOnExit": end_conference_on_exit, + "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": early_media, + "EarlyMedia": serialize.boolean_to_string(early_media), "MaxParticipants": max_participants, "ConferenceRecord": conference_record, "ConferenceTrim": conference_trim, @@ -664,13 +1549,14 @@ def create( "ConferenceRecordingStatusCallbackEvent": serialize.map( conference_recording_status_callback_event, lambda e: e ), - "Coaching": coaching, + "Coaching": serialize.boolean_to_string(coaching), "CallSidToCoach": call_sid_to_coach, "JitterBufferSize": jitter_buffer_size, "Byoc": byoc, "CallerId": caller_id, "CallReason": call_reason, "RecordingTrack": recording_track, + "RecordingConfigurationId": recording_configuration_id, "TimeLimit": time_limit, "MachineDetection": machine_detection, "MachineDetectionTimeout": machine_detection_timeout, @@ -679,15 +1565,188 @@ def create( "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, "AmdStatusCallback": amd_status_callback, "AmdStatusCallbackMethod": amd_status_callback_method, + "Trim": trim, + "CallToken": call_token, + "ClientNotificationUrl": client_notification_url, + "CallerDisplayName": caller_display_name, } ) + 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, + 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, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: 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 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. - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + :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, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, ) - return ParticipantInstance( self._version, payload, @@ -695,7 +1754,7 @@ def create( conference_sid=self._solution["conference_sid"], ) - async def create_async( + async def create_with_http_info_async( self, from_: str, to: str, @@ -737,6 +1796,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, @@ -745,12 +1805,16 @@ async def create_async( 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, - ) -> ParticipantInstance: + trim: Union[str, object] = values.unset, + call_token: Union[str, object] = values.unset, + client_notification_url: Union[str, object] = values.unset, + caller_display_name: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Asynchronously create the ParticipantInstance + 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, 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`. @@ -761,12 +1825,12 @@ 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`. :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 your recorded conference audio files. Can be: `trim-silence` or `do-not-trim` and defaults to `trim-silence`. + :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`. @@ -775,7 +1839,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'`. @@ -787,88 +1851,82 @@ 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. 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: 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`. - - :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, - "Timeout": timeout, - "Record": record, - "Muted": muted, - "Beep": beep, - "StartConferenceOnEnter": start_conference_on_enter, - "EndConferenceOnExit": end_conference_on_exit, - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "EarlyMedia": early_media, - "MaxParticipants": max_participants, - "ConferenceRecord": conference_record, - "ConferenceTrim": conference_trim, - "ConferenceStatusCallback": conference_status_callback, - "ConferenceStatusCallbackMethod": conference_status_callback_method, - "ConferenceStatusCallbackEvent": serialize.map( - conference_status_callback_event, lambda e: e - ), - "RecordingChannels": recording_channels, - "RecordingStatusCallback": recording_status_callback, - "RecordingStatusCallbackMethod": recording_status_callback_method, - "SipAuthUsername": sip_auth_username, - "SipAuthPassword": sip_auth_password, - "Region": region, - "ConferenceRecordingStatusCallback": conference_recording_status_callback, - "ConferenceRecordingStatusCallbackMethod": conference_recording_status_callback_method, - "RecordingStatusCallbackEvent": serialize.map( - recording_status_callback_event, lambda e: e - ), - "ConferenceRecordingStatusCallbackEvent": serialize.map( - conference_recording_status_callback_event, lambda e: e - ), - "Coaching": coaching, - "CallSidToCoach": call_sid_to_coach, - "JitterBufferSize": jitter_buffer_size, - "Byoc": byoc, - "CallerId": caller_id, - "CallReason": call_reason, - "RecordingTrack": recording_track, - "TimeLimit": time_limit, - "MachineDetection": machine_detection, - "MachineDetectionTimeout": machine_detection_timeout, - "MachineDetectionSpeechThreshold": machine_detection_speech_threshold, - "MachineDetectionSpeechEndThreshold": machine_detection_speech_end_threshold, - "MachineDetectionSilenceTimeout": machine_detection_silence_timeout, - "AmdStatusCallback": amd_status_callback, - "AmdStatusCallbackMethod": amd_status_callback_method, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + :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 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. + + :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, + client_notification_url=client_notification_url, + caller_display_name=caller_display_name, ) - - 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, @@ -936,6 +1994,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, @@ -961,6 +2083,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( muted=muted, @@ -996,6 +2119,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -1007,6 +2131,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, @@ -1031,17 +2223,23 @@ def page( """ data = values.of( { - "Muted": muted, - "Hold": hold, - "Coaching": coaching, + "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, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ParticipantPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -1067,19 +2265,111 @@ async def page_async( """ data = values.of( { - "Muted": muted, - "Hold": hold, - "Coaching": coaching, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ParticipantPage(self._version, response, self._solution) + 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: """ @@ -1091,7 +2381,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: """ @@ -1103,7 +2393,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 e9ac5789cb..cca644f741 100644 --- a/twilio/rest/api/v2010/account/conference/recording.py +++ b/twilio/rest/api/v2010/account/conference/recording.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,6 +24,7 @@ class RecordingInstance(InstanceResource): + class Source(object): DIALVERB = "DialVerb" CONFERENCE = "Conference" @@ -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 @@ -204,6 +278,7 @@ def __repr__(self) -> str: class RecordingContext(InstanceContext): + def __init__( self, version: Version, account_sid: str, conference_sid: str, sid: str ): @@ -227,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 @@ -234,9 +323,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -246,9 +357,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -258,19 +393,47 @@ def fetch(self) -> RecordingInstance: :returns: The fetched RecordingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], ) - return RecordingInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RecordingInstance: """ @@ -279,46 +442,74 @@ async def fetch_async(self) -> RecordingInstance: :returns: The fetched RecordingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + conference_sid=self._solution["conference_sid"], + sid=self._solution["sid"], ) - return RecordingInstance( + 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( + 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( { "Status": status, "PauseBehavior": pause_behavior, } ) + 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, + 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, @@ -327,32 +518,75 @@ 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( { "Status": status, "PauseBehavior": pause_behavior, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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: "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, @@ -361,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 @@ -372,12 +631,14 @@ def __repr__(self) -> str: class RecordingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: """ Build an instance of RecordingInstance :param payload: Payload response from the API """ + return RecordingInstance( self._version, payload, @@ -395,6 +656,7 @@ def __repr__(self) -> str: class RecordingList(ListResource): + def __init__(self, version: Version, account_sid: str, conference_sid: str): """ Initialize the RecordingList @@ -487,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, @@ -512,6 +844,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -547,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( @@ -558,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, @@ -591,8 +993,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RecordingPage(self._version, response, self._solution) + 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 RecordingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -627,10 +1035,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RecordingPage(self._version, response, self._solution) + 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: """ @@ -642,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: """ @@ -654,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 e34fbeae4d..6f6f0513c1 100644 --- a/twilio/rest/api/v2010/account/connect_app.py +++ b/twilio/rest/api/v2010/account/connect_app.py @@ -12,9 +12,9 @@ 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.api_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 +23,7 @@ class ConnectAppInstance(InstanceResource): + class Permission(object): GET_ALL = "get-all" POST_ALL = "post-all" @@ -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 @@ -215,6 +329,7 @@ def __repr__(self) -> str: class ConnectAppContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the ConnectAppContext @@ -234,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 @@ -241,9 +370,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -253,9 +404,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectAppInstance 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) -> ConnectAppInstance: @@ -265,18 +440,45 @@ def fetch(self) -> ConnectAppInstance: :returns: The fetched ConnectAppInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return ConnectAppInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectAppInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ConnectAppInstance: """ @@ -285,20 +487,31 @@ async def fetch_async(self) -> ConnectAppInstance: :returns: The fetched ConnectAppInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ConnectAppInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return ConnectAppInstance( + 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( + def _update( self, authorize_redirect_url: Union[str, object] = values.unset, company_name: Union[str, object] = values.unset, @@ -310,21 +523,14 @@ def update( permissions: Union[ List["ConnectAppInstance.Permission"], object ] = values.unset, - ) -> ConnectAppInstance: + ) -> tuple: """ - Update the ConnectAppInstance + Internal helper for update operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "AuthorizeRedirectUrl": authorize_redirect_url, @@ -337,13 +543,53 @@ def update( "Permissions": serialize.map(permissions, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -351,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, @@ -363,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. @@ -376,8 +622,46 @@ 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( { "AuthorizeRedirectUrl": authorize_redirect_url, @@ -390,13 +674,53 @@ async def update_async( "Permissions": serialize.map(permissions, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -404,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 @@ -415,12 +784,14 @@ def __repr__(self) -> str: class ConnectAppPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ConnectAppInstance: """ Build an instance of ConnectAppInstance :param payload: Payload response from the API """ + return ConnectAppInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -435,6 +806,7 @@ def __repr__(self) -> str: class ConnectAppList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the ConnectAppList @@ -501,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, @@ -520,6 +942,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -546,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( @@ -554,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, @@ -578,8 +1052,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ConnectAppPage(self._version, response, self._solution) + 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 ConnectAppPage(self._version, response, solution=self._solution) async def page_async( self, @@ -605,10 +1085,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ConnectAppPage(self._version, response, self._solution) + 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: """ @@ -620,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: """ @@ -632,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 121d2f03c8..948519d653 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/__init__.py @@ -12,10 +12,10 @@ 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 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 +30,7 @@ class IncomingPhoneNumberInstance(InstanceResource): + class AddressRequirement(object): NONE = "none" ANY = "any" @@ -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,110 +417,7 @@ async def update_async( bundle_sid=bundle_sid, ) - @property - def assigned_add_ons(self) -> AssignedAddOnList: - """ - Access the assigned_add_ons - """ - return self._proxy.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 IncomingPhoneNumberContext(InstanceContext): - def __init__(self, version: Version, account_sid: str, sid: str): - """ - Initialize the IncomingPhoneNumberContext - - :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 resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). - :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "account_sid": account_sid, - "sid": sid, - } - self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{sid}.json".format( - **self._solution - ) - - self._assigned_add_ons: Optional[AssignedAddOnList] = None - - def delete(self) -> bool: - """ - Deletes the IncomingPhoneNumberInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the IncomingPhoneNumberInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> IncomingPhoneNumberInstance: - """ - Fetch the IncomingPhoneNumberInstance - - - :returns: The fetched IncomingPhoneNumberInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> IncomingPhoneNumberInstance: - """ - Asynchronous coroutine to fetch the IncomingPhoneNumberInstance - - - :returns: The fetched IncomingPhoneNumberInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], - ) - - def update( + def update_with_http_info( self, account_sid: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -509,9 +446,9 @@ def update( identity_sid: Union[str, object] = values.unset, address_sid: Union[str, object] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> IncomingPhoneNumberInstance: + ) -> ApiResponse: """ - Update the IncomingPhoneNumberInstance + 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`. @@ -537,50 +474,35 @@ def update( :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: ApiResponse with instance, status code, and 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": 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, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], + 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_async( + async def update_with_http_info_async( self, account_sid: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -609,9 +531,9 @@ async def update_async( identity_sid: Union[str, object] = values.unset, address_sid: Union[str, object] = values.unset, bundle_sid: Union[str, object] = values.unset, - ) -> IncomingPhoneNumberInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the IncomingPhoneNumberInstance + 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`. @@ -637,47 +559,32 @@ async def update_async( :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: ApiResponse with instance, status code, and 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": 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, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return IncomingPhoneNumberInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], + 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 @@ -685,13 +592,7 @@ 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 + return self._proxy.assigned_add_ons def __repr__(self) -> str: """ @@ -700,19 +601,747 @@ 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 IncomingPhoneNumberPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> IncomingPhoneNumberInstance: - """ - Build an instance of IncomingPhoneNumberInstance +class IncomingPhoneNumberContext(InstanceContext): - :param payload: Payload response from the API + def __init__(self, version: Version, account_sid: str, sid: str): """ - return IncomingPhoneNumberInstance( - self._version, payload, account_sid=self._solution["account_sid"] - ) + Initialize the IncomingPhoneNumberContext + + :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 resource to update. For more information, see [Exchanging Numbers Between Subaccounts](https://www.twilio.com/docs/iam/api/subaccounts#exchanging-numbers). + :param sid: The Twilio-provided string that uniquely identifies the IncomingPhoneNumber resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "sid": sid, + } + self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers/{sid}.json".format( + **self._solution + ) + + 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 + + + :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 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 IncomingPhoneNumberInstance + + + :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 IncomingPhoneNumberInstance 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) -> IncomingPhoneNumberInstance: + """ + Fetch the IncomingPhoneNumberInstance + + + :returns: The fetched IncomingPhoneNumberInstance + """ + payload, _, _ = self._fetch() + return IncomingPhoneNumberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IncomingPhoneNumberInstance and return response metadata + + + :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" + + 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, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], + ) + + 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, + 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 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 self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + 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: + """ + 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, _, _ = 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, + account_sid=self._solution["account_sid"], + sid=self._solution["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 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 = 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: """ @@ -724,28 +1353,107 @@ def __repr__(self) -> str: 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. + :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( + { + "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, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_sid, + "PhoneNumber": phone_number, + "AreaCode": area_code, + } + ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - """ - super().__init__(version) + headers["Accept"] = "application/json" - # Path Solution - self._solution = { - "account_sid": account_sid, - } - self._uri = "/Accounts/{account_sid}/IncomingPhoneNumbers.json".format( - **self._solution + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - 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, @@ -807,6 +1515,166 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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). + + :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( { "ApiVersion": api_version, @@ -819,7 +1687,9 @@ def create( "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, "VoiceApplicationSid": voice_application_sid, - "VoiceCallerIdLookup": voice_caller_id_lookup, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), "VoiceFallbackMethod": voice_fallback_method, "VoiceFallbackUrl": voice_fallback_url, "VoiceMethod": voice_method, @@ -835,18 +1705,108 @@ def create( "AreaCode": area_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, + 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). - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + :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_async( + async def create_with_http_info_async( self, api_version: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -876,9 +1836,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 + 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. @@ -905,46 +1865,38 @@ 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 """ - data = values.of( - { - "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": 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, - "IdentitySid": identity_sid, - "AddressSid": address_sid, - "VoiceReceiveMode": voice_receive_mode, - "BundleSid": bundle_sid, - "PhoneNumber": phone_number, - "AreaCode": area_code, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, @@ -1024,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, @@ -1051,6 +2079,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -1089,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( @@ -1101,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, @@ -1127,7 +2231,7 @@ def page( """ data = values.of( { - "Beta": beta, + "Beta": serialize.boolean_to_string(beta), "FriendlyName": friendly_name, "PhoneNumber": phone_number, "Origin": origin, @@ -1137,8 +2241,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return IncomingPhoneNumberPage(self._version, response, self._solution) + 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 IncomingPhoneNumberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1166,7 +2276,7 @@ async def page_async( """ data = values.of( { - "Beta": beta, + "Beta": serialize.boolean_to_string(beta), "FriendlyName": friendly_name, "PhoneNumber": phone_number, "Origin": origin, @@ -1176,10 +2286,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return IncomingPhoneNumberPage(self._version, response, self._solution) + 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: """ @@ -1191,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: """ @@ -1203,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 4b04d75256..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 @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class AssignedAddOnInstance(InstanceResource): - """ :ivar sid: The unique string that that we created to identify the resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. @@ -75,6 +74,7 @@ def __init__( "resource_sid": resource_sid, "sid": sid or self.sid, } + self._context: Optional[AssignedAddOnContext] = None @property @@ -112,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 @@ -130,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: """ @@ -148,6 +184,7 @@ def __repr__(self) -> str: class AssignedAddOnContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, resource_sid: str, sid: str): """ Initialize the AssignedAddOnContext @@ -171,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 @@ -178,9 +229,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -190,9 +263,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssignedAddOnInstance 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) -> AssignedAddOnInstance: @@ -202,19 +299,47 @@ def fetch(self) -> AssignedAddOnInstance: :returns: The fetched AssignedAddOnInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], ) - return AssignedAddOnInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssignedAddOnInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AssignedAddOnInstance: """ @@ -223,19 +348,31 @@ async def fetch_async(self) -> AssignedAddOnInstance: :returns: The fetched AssignedAddOnInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AssignedAddOnInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + resource_sid=self._solution["resource_sid"], + sid=self._solution["sid"], ) - return AssignedAddOnInstance( + 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: @@ -262,12 +399,14 @@ def __repr__(self) -> str: class AssignedAddOnPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnInstance: """ Build an instance of AssignedAddOnInstance :param payload: Payload response from the API """ + return AssignedAddOnInstance( self._version, payload, @@ -285,6 +424,7 @@ def __repr__(self) -> str: class AssignedAddOnList(ListResource): + def __init__(self, version: Version, account_sid: str, resource_sid: str): """ Initialize the AssignedAddOnList @@ -305,26 +445,38 @@ 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( { "InstalledAddOnSid": installed_add_on_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -332,26 +484,59 @@ 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( { "InstalledAddOnSid": installed_add_on_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, + 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, @@ -359,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, @@ -409,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, @@ -428,6 +684,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -454,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( @@ -462,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, @@ -486,8 +794,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AssignedAddOnPage(self._version, response, self._solution) + 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 AssignedAddOnPage(self._version, response, solution=self._solution) async def page_async( self, @@ -513,10 +827,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return AssignedAddOnPage(self._version, response, self._solution) + 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: """ @@ -528,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: """ @@ -540,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 54b1c2a80b..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 @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class AssignedAddOnExtensionInstance(InstanceResource): - """ :ivar sid: The unique string that that we created to identify the resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the resource. @@ -63,6 +62,7 @@ def __init__( "assigned_add_on_sid": assigned_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[AssignedAddOnExtensionContext] = None @property @@ -101,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 @@ -112,6 +130,7 @@ def __repr__(self) -> str: class AssignedAddOnExtensionContext(InstanceContext): + def __init__( self, version: Version, @@ -142,6 +161,22 @@ def __init__( **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) -> AssignedAddOnExtensionInstance: """ Fetch the AssignedAddOnExtensionInstance @@ -149,13 +184,25 @@ def fetch(self) -> AssignedAddOnExtensionInstance: :returns: The fetched AssignedAddOnExtensionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return 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 AssignedAddOnExtensionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssignedAddOnExtensionInstance and return response metadata + + + :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"], @@ -163,6 +210,23 @@ def fetch(self) -> AssignedAddOnExtensionInstance: 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AssignedAddOnExtensionInstance: """ @@ -171,13 +235,25 @@ async def fetch_async(self) -> AssignedAddOnExtensionInstance: :returns: The fetched AssignedAddOnExtensionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return 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 AssignedAddOnExtensionInstance( + 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"], @@ -185,6 +261,7 @@ async def fetch_async(self) -> AssignedAddOnExtensionInstance: 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: """ @@ -197,12 +274,14 @@ def __repr__(self) -> str: class AssignedAddOnExtensionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AssignedAddOnExtensionInstance: """ Build an instance of AssignedAddOnExtensionInstance :param payload: Payload response from the API """ + return AssignedAddOnExtensionInstance( self._version, payload, @@ -221,6 +300,7 @@ def __repr__(self) -> str: class AssignedAddOnExtensionList(ListResource): + def __init__( self, version: Version, @@ -299,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, @@ -318,6 +448,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -344,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( @@ -352,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, @@ -376,8 +558,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AssignedAddOnExtensionPage(self._version, response, self._solution) + 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 AssignedAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -403,10 +593,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 ) - return AssignedAddOnExtensionPage(self._version, response, self._solution) + 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: """ @@ -418,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: """ @@ -430,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 4af79dcf8a..06ce14ba9f 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/local.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/local.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class LocalInstance(InstanceResource): + class AddressRequirement(object): NONE = "none" ANY = "any" @@ -88,9 +89,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.address_sid: Optional[str] = payload.get("address_sid") - self.address_requirements: Optional[ - "LocalInstance.AddressRequirement" - ] = payload.get("address_requirements") + self.address_requirements: Optional["LocalInstance.AddressRequirement"] = ( + payload.get("address_requirements") + ) self.api_version: Optional[str] = payload.get("api_version") self.beta: Optional[bool] = payload.get("beta") self.capabilities: Optional[str] = payload.get("capabilities") @@ -116,9 +117,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): ) self.trunk_sid: Optional[str] = payload.get("trunk_sid") self.uri: Optional[str] = payload.get("uri") - self.voice_receive_mode: Optional[ - "LocalInstance.VoiceReceiveMode" - ] = payload.get("voice_receive_mode") + self.voice_receive_mode: Optional["LocalInstance.VoiceReceiveMode"] = ( + payload.get("voice_receive_mode") + ) self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") self.voice_caller_id_lookup: Optional[bool] = payload.get( "voice_caller_id_lookup" @@ -152,12 +153,14 @@ def __repr__(self) -> str: class LocalPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> LocalInstance: """ Build an instance of LocalInstance :param payload: Payload response from the API """ + return LocalInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -172,6 +175,7 @@ def __repr__(self) -> str: class LocalList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the LocalList @@ -190,6 +194,80 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "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, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_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, @@ -247,6 +325,157 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "PhoneNumber": phone_number, @@ -260,7 +489,9 @@ def create( "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, "VoiceApplicationSid": voice_application_sid, - "VoiceCallerIdLookup": voice_caller_id_lookup, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), "VoiceFallbackMethod": voice_fallback_method, "VoiceFallbackUrl": voice_fallback_url, "VoiceMethod": voice_method, @@ -274,15 +505,14 @@ def create( "BundleSid": bundle_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return LocalInstance( - self._version, payload, account_sid=self._solution["account_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( @@ -342,43 +572,121 @@ async def create_async( :returns: The created LocalInstance """ - data = values.of( - { - "PhoneNumber": phone_number, - "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": voice_caller_id_lookup, - "VoiceFallbackMethod": voice_fallback_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceMethod": voice_method, - "VoiceUrl": voice_url, - "IdentitySid": identity_sid, - "AddressSid": address_sid, - "EmergencyStatus": emergency_status, - "EmergencyAddressSid": emergency_address_sid, - "TrunkSid": trunk_sid, - "VoiceReceiveMode": voice_receive_mode, - "BundleSid": bundle_sid, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return LocalInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return LocalInstance( + 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, @@ -458,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, @@ -485,6 +869,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -523,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( @@ -535,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, @@ -561,7 +1021,7 @@ def page( """ data = values.of( { - "Beta": beta, + "Beta": serialize.boolean_to_string(beta), "FriendlyName": friendly_name, "PhoneNumber": phone_number, "Origin": origin, @@ -571,8 +1031,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return LocalPage(self._version, response, self._solution) + 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 LocalPage(self._version, response, solution=self._solution) async def page_async( self, @@ -600,7 +1066,7 @@ async def page_async( """ data = values.of( { - "Beta": beta, + "Beta": serialize.boolean_to_string(beta), "FriendlyName": friendly_name, "PhoneNumber": phone_number, "Origin": origin, @@ -610,10 +1076,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return LocalPage(self._version, response, self._solution) + 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: """ @@ -625,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: """ @@ -637,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 2ab5a652c5..2087c91ae3 100644 --- a/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py +++ b/twilio/rest/api/v2010/account/incoming_phone_number/mobile.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class MobileInstance(InstanceResource): + class AddressRequirement(object): NONE = "none" ANY = "any" @@ -88,9 +89,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.address_sid: Optional[str] = payload.get("address_sid") - self.address_requirements: Optional[ - "MobileInstance.AddressRequirement" - ] = payload.get("address_requirements") + self.address_requirements: Optional["MobileInstance.AddressRequirement"] = ( + payload.get("address_requirements") + ) self.api_version: Optional[str] = payload.get("api_version") self.beta: Optional[bool] = payload.get("beta") self.capabilities: Optional[str] = payload.get("capabilities") @@ -116,9 +117,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): ) self.trunk_sid: Optional[str] = payload.get("trunk_sid") self.uri: Optional[str] = payload.get("uri") - self.voice_receive_mode: Optional[ - "MobileInstance.VoiceReceiveMode" - ] = payload.get("voice_receive_mode") + self.voice_receive_mode: Optional["MobileInstance.VoiceReceiveMode"] = ( + payload.get("voice_receive_mode") + ) self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") self.voice_caller_id_lookup: Optional[bool] = payload.get( "voice_caller_id_lookup" @@ -152,12 +153,14 @@ def __repr__(self) -> str: class MobilePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MobileInstance: """ Build an instance of MobileInstance :param payload: Payload response from the API """ + return MobileInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -172,6 +175,7 @@ def __repr__(self) -> str: class MobileList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the MobileList @@ -190,6 +194,82 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "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, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_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, @@ -249,6 +329,161 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "PhoneNumber": phone_number, @@ -262,7 +497,9 @@ def create( "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, "VoiceApplicationSid": voice_application_sid, - "VoiceCallerIdLookup": voice_caller_id_lookup, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), "VoiceFallbackMethod": voice_fallback_method, "VoiceFallbackUrl": voice_fallback_url, "VoiceMethod": voice_method, @@ -276,15 +513,14 @@ def create( "BundleSid": bundle_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return MobileInstance( - self._version, payload, account_sid=self._solution["account_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( @@ -346,43 +582,123 @@ async def create_async( :returns: The created MobileInstance """ - data = values.of( - { - "PhoneNumber": phone_number, - "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": voice_caller_id_lookup, - "VoiceFallbackMethod": voice_fallback_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceMethod": voice_method, - "VoiceUrl": voice_url, - "IdentitySid": identity_sid, - "AddressSid": address_sid, - "EmergencyStatus": emergency_status, - "EmergencyAddressSid": emergency_address_sid, - "TrunkSid": trunk_sid, - "VoiceReceiveMode": voice_receive_mode, - "BundleSid": bundle_sid, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return MobileInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return MobileInstance( + 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, @@ -462,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, @@ -489,6 +881,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -527,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( @@ -539,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, @@ -565,7 +1033,7 @@ def page( """ data = values.of( { - "Beta": beta, + "Beta": serialize.boolean_to_string(beta), "FriendlyName": friendly_name, "PhoneNumber": phone_number, "Origin": origin, @@ -575,8 +1043,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MobilePage(self._version, response, self._solution) + 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 MobilePage(self._version, response, solution=self._solution) async def page_async( self, @@ -604,7 +1078,7 @@ async def page_async( """ data = values.of( { - "Beta": beta, + "Beta": serialize.boolean_to_string(beta), "FriendlyName": friendly_name, "PhoneNumber": phone_number, "Origin": origin, @@ -614,10 +1088,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MobilePage(self._version, response, self._solution) + 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: """ @@ -629,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: """ @@ -641,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 3b995504a5..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 @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class TollFreeInstance(InstanceResource): + class AddressRequirement(object): NONE = "none" ANY = "any" @@ -88,9 +89,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.account_sid: Optional[str] = payload.get("account_sid") self.address_sid: Optional[str] = payload.get("address_sid") - self.address_requirements: Optional[ - "TollFreeInstance.AddressRequirement" - ] = payload.get("address_requirements") + self.address_requirements: Optional["TollFreeInstance.AddressRequirement"] = ( + payload.get("address_requirements") + ) self.api_version: Optional[str] = payload.get("api_version") self.beta: Optional[bool] = payload.get("beta") self.capabilities: Optional[str] = payload.get("capabilities") @@ -116,9 +117,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): ) self.trunk_sid: Optional[str] = payload.get("trunk_sid") self.uri: Optional[str] = payload.get("uri") - self.voice_receive_mode: Optional[ - "TollFreeInstance.VoiceReceiveMode" - ] = payload.get("voice_receive_mode") + self.voice_receive_mode: Optional["TollFreeInstance.VoiceReceiveMode"] = ( + payload.get("voice_receive_mode") + ) self.voice_application_sid: Optional[str] = payload.get("voice_application_sid") self.voice_caller_id_lookup: Optional[bool] = payload.get( "voice_caller_id_lookup" @@ -127,9 +128,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], account_sid: str): self.voice_fallback_url: Optional[str] = payload.get("voice_fallback_url") self.voice_method: Optional[str] = payload.get("voice_method") self.voice_url: Optional[str] = payload.get("voice_url") - self.emergency_status: Optional[ - "TollFreeInstance.EmergencyStatus" - ] = payload.get("emergency_status") + self.emergency_status: Optional["TollFreeInstance.EmergencyStatus"] = ( + payload.get("emergency_status") + ) self.emergency_address_sid: Optional[str] = payload.get("emergency_address_sid") self.emergency_address_status: Optional[ "TollFreeInstance.EmergencyAddressStatus" @@ -152,12 +153,14 @@ def __repr__(self) -> str: class TollFreePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TollFreeInstance: """ Build an instance of TollFreeInstance :param payload: Payload response from the API """ + return TollFreeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -172,6 +175,7 @@ def __repr__(self) -> str: class TollFreeList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the TollFreeList @@ -190,6 +194,82 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "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, + "IdentitySid": identity_sid, + "AddressSid": address_sid, + "EmergencyStatus": emergency_status, + "EmergencyAddressSid": emergency_address_sid, + "TrunkSid": trunk_sid, + "VoiceReceiveMode": voice_receive_mode, + "BundleSid": bundle_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, @@ -249,6 +329,161 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "PhoneNumber": phone_number, @@ -262,7 +497,9 @@ def create( "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, "VoiceApplicationSid": voice_application_sid, - "VoiceCallerIdLookup": voice_caller_id_lookup, + "VoiceCallerIdLookup": serialize.boolean_to_string( + voice_caller_id_lookup + ), "VoiceFallbackMethod": voice_fallback_method, "VoiceFallbackUrl": voice_fallback_url, "VoiceMethod": voice_method, @@ -276,15 +513,14 @@ def create( "BundleSid": bundle_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return TollFreeInstance( - self._version, payload, account_sid=self._solution["account_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( @@ -346,43 +582,123 @@ async def create_async( :returns: The created TollFreeInstance """ - data = values.of( - { - "PhoneNumber": phone_number, - "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": voice_caller_id_lookup, - "VoiceFallbackMethod": voice_fallback_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceMethod": voice_method, - "VoiceUrl": voice_url, - "IdentitySid": identity_sid, - "AddressSid": address_sid, - "EmergencyStatus": emergency_status, - "EmergencyAddressSid": emergency_address_sid, - "TrunkSid": trunk_sid, - "VoiceReceiveMode": voice_receive_mode, - "BundleSid": bundle_sid, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return TollFreeInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return TollFreeInstance( + 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, @@ -462,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, @@ -489,6 +881,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( beta=beta, @@ -527,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( @@ -539,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, @@ -565,7 +1033,7 @@ def page( """ data = values.of( { - "Beta": beta, + "Beta": serialize.boolean_to_string(beta), "FriendlyName": friendly_name, "PhoneNumber": phone_number, "Origin": origin, @@ -575,8 +1043,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TollFreePage(self._version, response, self._solution) + 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 TollFreePage(self._version, response, solution=self._solution) async def page_async( self, @@ -604,7 +1078,7 @@ async def page_async( """ data = values.of( { - "Beta": beta, + "Beta": serialize.boolean_to_string(beta), "FriendlyName": friendly_name, "PhoneNumber": phone_number, "Origin": origin, @@ -614,10 +1088,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return TollFreePage(self._version, response, self._solution) + 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: """ @@ -629,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: """ @@ -641,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 76c8f1d55c..2683e7ab3c 100644 --- a/twilio/rest/api/v2010/account/key.py +++ b/twilio/rest/api/v2010/account/key.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class KeyInstance(InstanceResource): - """ :ivar sid: The unique string that that we created to identify the Key resource. :ivar friendly_name: The string that you assigned to describe the resource. @@ -54,6 +53,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[KeyContext] = None @property @@ -90,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 @@ -108,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 @@ -134,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 @@ -145,6 +209,7 @@ def __repr__(self) -> str: class KeyContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the KeyContext @@ -162,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 @@ -169,9 +248,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -181,9 +282,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the KeyInstance 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) -> KeyInstance: @@ -193,18 +318,45 @@ def fetch(self) -> KeyInstance: :returns: The fetched KeyInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return KeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return KeyInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KeyInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> KeyInstance: """ @@ -213,12 +365,7 @@ async def fetch_async(self) -> KeyInstance: :returns: The fetched KeyInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return KeyInstance( self._version, payload, @@ -226,26 +373,54 @@ 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( { "FriendlyName": friendly_name, } ) + 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, + 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, @@ -253,28 +428,61 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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 + ) -> 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, @@ -282,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 @@ -293,12 +522,14 @@ def __repr__(self) -> str: class KeyPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> KeyInstance: """ Build an instance of KeyInstance :param payload: Payload response from the API """ + return KeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -313,6 +544,7 @@ def __repr__(self) -> str: class KeyList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the KeyList @@ -379,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, @@ -398,6 +680,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -424,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( @@ -432,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, @@ -456,8 +790,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return KeyPage(self._version, response, self._solution) + 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 KeyPage(self._version, response, solution=self._solution) async def page_async( self, @@ -483,10 +823,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return KeyPage(self._version, response, self._solution) + 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: """ @@ -498,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: """ @@ -510,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 476c023605..38182a2c9b 100644 --- a/twilio/rest/api/v2010/account/message/__init__.py +++ b/twilio/rest/api/v2010/account/message/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,11 +26,14 @@ class MessageInstance(InstanceResource): + class AddressRetention(object): RETAIN = "retain" + OBFUSCATE = "obfuscate" class ContentRetention(object): RETAIN = "retain" + DISCARD = "discard" class Direction(object): INBOUND = "inbound" @@ -38,6 +41,10 @@ class Direction(object): OUTBOUND_CALL = "outbound-call" OUTBOUND_REPLY = "outbound-reply" + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" + class ScheduleType(object): FIXED = "fixed" @@ -56,29 +63,32 @@ class Status(object): PARTIALLY_DELIVERED = "partially_delivered" CANCELED = "canceled" + class TrafficType(object): + FREE = "free" + class UpdateStatus(object): CANCELED = "canceled" """ - :ivar body: The message text. Can be up to 1,600 characters long. - :ivar num_segments: The number of segments that make up the complete message. A message body that is too large to be sent in a single SMS message is segmented and charged as multiple messages. Inbound messages over 160 characters are reassembled when the message is received. Note: When using a Messaging Service to send messages, `num_segments` will always be 0 in Twilio's response to your API request. + :ivar body: The text content of the message + :ivar num_segments: The number of segments that make up the complete message. SMS message bodies that exceed the [character limit](https://www.twilio.com/docs/glossary/what-sms-character-limit) are segmented and charged as multiple messages. Note: For messages sent via a Messaging Service, `num_segments` is initially `0`, since a sender hasn't yet been assigned. :ivar direction: - :ivar _from: The phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format), [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), or [Wireless SIM](https://www.twilio.com/docs/wireless/tutorials/communications-guides/how-to-send-and-receive-text-messages) that initiated the message. For incoming messages, this will be the number of the sending phone. For outgoing messages, this value will be one of your Twilio phone numbers or the alphanumeric sender ID used. - :ivar to: The phone number in [E.164](https://en.wikipedia.org/wiki/E.164) format that received the message. For incoming messages, this will be one of your Twilio phone numbers. For outgoing messages, this will be the sending phone. - :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 price: The amount billed for the message, in the currency specified by `price_unit`. Note that your account is charged for each segment we send to the handset. Populated after the message has been sent. May not be immediately available. - :ivar error_message: The description of the `error_code` if your message `status` is `failed` or `undelivered`. If the message was successful, this value is null. - :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that sent the message that created the resource. - :ivar num_media: The number of media files associated with the message. A message can send up to 10 media files. + :ivar from_: The sender's 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`). For incoming messages, this is the number or channel address of the sender. For outgoing messages, this value is a Twilio phone number, alphanumeric sender ID, short code, or channel address from which the message is sent. + :ivar to: The recipient's phone number (in [E.164](https://en.wikipedia.org/wiki/E.164) format) or [channel address](https://www.twilio.com/docs/messaging/channels) (e.g. `whatsapp:+15552229999`) + :ivar date_updated: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was last updated + :ivar price: The amount billed for the message in the currency specified by `price_unit`. The `price` is populated after the message has been sent/received, and may not be immediately availalble. View the [Pricing page](https://www.twilio.com/en-us/pricing) for more details. + :ivar error_message: The description of the `error_code` if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. + :ivar uri: The URI of the Message resource, relative to `https://api.twilio.com`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource + :ivar num_media: The number of media files associated with the Message resource. :ivar status: - :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/services/api) used with the message. The value is null if a Messaging Service was not used. - :ivar sid: The unique string that that we created to identify the Message resource. - :ivar date_sent: The date and time in GMT that the resource was sent specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. For outgoing messages, this is when we sent the message. For incoming messages, this is when we made the HTTP request to your application. - :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 error_code: The error code returned if your message `status` is `failed` or `undelivered`. The error_code provides more information about the failure. If the message was successful, this value is null. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) associated with the Message resource. A unique default value is assigned if a Messaging Service is not used. + :ivar sid: The unique, Twilio-provided string that identifies the Message resource. + :ivar date_sent: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message was sent. For an outgoing message, this is when Twilio sent the message. For an incoming message, this is when Twilio sent the HTTP request to your incoming message webhook URL. + :ivar date_created: The [RFC 2822](https://datatracker.ietf.org/doc/html/rfc2822#section-3.3) timestamp (in GMT) of when the Message resource was created + :ivar error_code: The [error code](https://www.twilio.com/docs/api/errors) returned if the Message `status` is `failed` or `undelivered`. If no error was encountered, the value is `null`. The value returned in this field for a specific error cause is subject to change as Twilio improves errors. Users should not use the `error_code` and `error_message` fields programmatically. :ivar price_unit: The currency in which `price` is measured, in [ISO 4127](https://www.iso.org/iso/home/standards/currency_codes.htm) format (e.g. `usd`, `eur`, `jpy`). - :ivar api_version: The API version used to process the message. + :ivar api_version: The API version used to process the Message :ivar subresource_uris: A list of related resources identified by their URIs relative to `https://api.twilio.com` """ @@ -94,7 +104,7 @@ def __init__( self.body: Optional[str] = payload.get("body") self.num_segments: Optional[str] = payload.get("num_segments") self.direction: Optional["MessageInstance.Direction"] = payload.get("direction") - self._from: Optional[str] = payload.get("from") + self.from_: Optional[str] = payload.get("from") self.to: Optional[str] = payload.get("to") self.date_updated: Optional[datetime] = deserialize.rfc2822_datetime( payload.get("date_updated") @@ -124,6 +134,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[MessageContext] = None @property @@ -160,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 @@ -178,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, @@ -186,7 +233,7 @@ def update( """ Update the MessageInstance - :param body: The text of the message you want to send. Can be up to 1,600 characters long. + :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 @@ -204,7 +251,7 @@ async def update_async( """ Asynchronous coroutine to update the MessageInstance - :param body: The text of the message you want to send. Can be up to 1,600 characters long. + :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 @@ -214,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: """ @@ -239,13 +322,14 @@ def __repr__(self) -> str: class MessageContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the MessageContext :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 Message resources to update. - :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + :param sid: The SID of the Message resource to be updated """ super().__init__(version) @@ -261,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 @@ -268,9 +366,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -280,9 +400,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance 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) -> MessageInstance: @@ -292,18 +436,45 @@ def fetch(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MessageInstance: """ @@ -312,45 +483,72 @@ async def fetch_async(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MessageInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + 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( + def _update( self, body: Union[str, object] = values.unset, status: Union["MessageInstance.UpdateStatus", object] = values.unset, - ) -> MessageInstance: + ) -> tuple: """ - Update the MessageInstance - - :param body: The text of the message you want to send. Can be up to 1,600 characters long. - :param status: + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Body": body, "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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[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, @@ -358,32 +556,70 @@ 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 text of the message you want to send. Can be up to 1,600 characters long. + :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( { "Body": body, "Status": status, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -391,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: """ @@ -428,12 +688,14 @@ def __repr__(self) -> str: 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, account_sid=self._solution["account_sid"] ) @@ -448,12 +710,13 @@ def __repr__(self) -> str: class MessageList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the MessageList :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 Message resources to read. + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resources. """ super().__init__(version) @@ -464,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, @@ -482,83 +745,67 @@ 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, send_as_mms: Union[bool, object] = values.unset, - content_sid: Union[str, 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, - ) -> MessageInstance: + content_sid: Union[str, object] = values.unset, + ) -> tuple: """ - Create the MessageInstance - - :param to: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format for SMS/MMS or [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses) for other 3rd-party channels. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If specified, we POST these message status changes to the URL: `queued`, `failed`, `sent`, `delivered`, or `undelivered`. Twilio will POST its [standard request parameters](https://www.twilio.com/docs/sms/twiml#request-parameters) as well as some additional parameters including `MessageSid`, `MessageStatus`, and `ErrorCode`. If you include this parameter with the `messaging_service_sid`, we use this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/sms/services/api). URLs must contain a valid hostname and underscores are not allowed. - :param application_sid: The SID of the application that should receive message status. We POST a `message_sid` parameter and a `message_status` parameter with a value of `sent` or `failed` to the [application](https://www.twilio.com/docs/usage/api/applications)'s `message_status_callback`. If a `status_callback` parameter is also passed, it will be ignored and the application's `message_status_callback` parameter will be used. - :param max_price: The maximum total price in US dollars that you will pay for the message to be delivered. Can be a decimal value that has up to 4 decimal places. All messages are queued for delivery and the message cost is checked before the message is sent. If the cost exceeds `max_price`, the message will fail and a status of `Failed` is sent to the status callback. If `MaxPrice` is not set, the message cost is not checked. - :param provide_feedback: Whether to confirm delivery of the message. Set this value to `true` if you are sending messages that have a trackable user action and you intend to confirm delivery of the message using the [Message Feedback API](https://www.twilio.com/docs/sms/api/message-feedback-resource). This parameter is `false` by default. - :param attempt: Total number of attempts made ( including this ) to send out the message regardless of the provider used - :param validity_period: How long in seconds the message can remain in our outgoing message queue. After this period elapses, the message fails and we call your status callback. Can be between 1 and the default value of 14,400 seconds. After a message has been accepted by a carrier, however, we cannot guarantee that the message will not be queued after this period. We recommend that this value be at least 5 seconds. - :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 Channels Messages. - :param shorten_urls: Determines the usage of Click Tracking. Setting it to `true` will instruct Twilio to replace all links in the Message with a shortened version based on the associated Domain Sid and track clicks on them. If this parameter is not set on an API call, we will use the value set on the Messaging Service. If this parameter is not set and the value is not configured on the Messaging Service used this will default to `false`. - :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 will deliver the message as a single MMS message, regardless of the presence of media. - :param content_sid: The SID of the Content object returned at Content API content create time (https://www.twilio.com/docs/content-api/create-and-send-your-first-content-api-template#create-a-template). If this parameter is not specified, then the Content API will not be utilized. - :param content_variables: Key-value pairs of variable names to substitution values, used alongside a content_sid. If not specified, Content API will default to the default variables defined at create time. - :param from_: A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, an [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses) that is enabled for the type of message you want to send. Phone numbers or [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from Twilio also work here. You cannot, for example, spoof messages from a private cell phone number. If you are using `messaging_service_sid`, this parameter must be empty. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/services#send-a-message-with-copilot) you want to associate with the Message. Set this parameter to use the [Messaging Service Settings and Copilot Features](https://www.twilio.com/console/sms/services) you have configured and leave the `from` parameter empty. When only this parameter is set, Twilio will use your enabled Copilot Features to select the `from` phone number for delivery. - :param body: The text of the message you want to send. Can be up to 1,600 characters in length. - :param media_url: The URL of the media to send with the message. The media can be of type `gif`, `png`, and `jpeg` and will be formatted correctly on the recipient's device. The media size limit is 5MB for supported file types (JPEG, PNG, GIF) and 500KB for [other types](https://www.twilio.com/docs/sms/accepted-mime-types) of accepted media. To send more than one image in the message body, provide multiple `media_url` parameters in the POST request. You can include up to 10 `media_url` parameters per message. You can send images in an SMS message in only the US and Canada. + Internal helper for create operation - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "To": to, "StatusCallback": status_callback, "ApplicationSid": application_sid, "MaxPrice": max_price, - "ProvideFeedback": provide_feedback, + "ProvideFeedback": serialize.boolean_to_string(provide_feedback), "Attempt": attempt, "ValidityPeriod": validity_period, - "ForceDelivery": force_delivery, + "ForceDelivery": serialize.boolean_to_string(force_delivery), "ContentRetention": content_retention, "AddressRetention": address_retention, - "SmartEncoded": smart_encoded, + "SmartEncoded": serialize.boolean_to_string(smart_encoded), "PersistentAction": serialize.map(persistent_action, lambda e: e), - "ShortenUrls": shorten_urls, + "TrafficType": traffic_type, + "ShortenUrls": serialize.boolean_to_string(shorten_urls), "ScheduleType": schedule_type, "SendAt": serialize.iso8601_datetime(send_at), - "SendAsMms": send_as_mms, - "ContentSid": content_sid, + "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"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return MessageInstance( - self._version, payload, account_sid=self._solution["account_sid"] + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - async def create_async( + def create( self, to: str, status_callback: Union[str, object] = values.unset, @@ -576,87 +823,449 @@ 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, send_as_mms: Union[bool, object] = values.unset, - content_sid: Union[str, 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 + Create the MessageInstance - :param to: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format for SMS/MMS or [Channel user address](https://www.twilio.com/docs/sms/channels#channel-addresses) for other 3rd-party channels. - :param status_callback: The URL we should call using the `status_callback_method` to send status information to your application. If specified, we POST these message status changes to the URL: `queued`, `failed`, `sent`, `delivered`, or `undelivered`. Twilio will POST its [standard request parameters](https://www.twilio.com/docs/sms/twiml#request-parameters) as well as some additional parameters including `MessageSid`, `MessageStatus`, and `ErrorCode`. If you include this parameter with the `messaging_service_sid`, we use this URL instead of the Status Callback URL of the [Messaging Service](https://www.twilio.com/docs/sms/services/api). URLs must contain a valid hostname and underscores are not allowed. - :param application_sid: The SID of the application that should receive message status. We POST a `message_sid` parameter and a `message_status` parameter with a value of `sent` or `failed` to the [application](https://www.twilio.com/docs/usage/api/applications)'s `message_status_callback`. If a `status_callback` parameter is also passed, it will be ignored and the application's `message_status_callback` parameter will be used. - :param max_price: The maximum total price in US dollars that you will pay for the message to be delivered. Can be a decimal value that has up to 4 decimal places. All messages are queued for delivery and the message cost is checked before the message is sent. If the cost exceeds `max_price`, the message will fail and a status of `Failed` is sent to the status callback. If `MaxPrice` is not set, the message cost is not checked. - :param provide_feedback: Whether to confirm delivery of the message. Set this value to `true` if you are sending messages that have a trackable user action and you intend to confirm delivery of the message using the [Message Feedback API](https://www.twilio.com/docs/sms/api/message-feedback-resource). This parameter is `false` by default. - :param attempt: Total number of attempts made ( including this ) to send out the message regardless of the provider used - :param validity_period: How long in seconds the message can remain in our outgoing message queue. After this period elapses, the message fails and we call your status callback. Can be between 1 and the default value of 14,400 seconds. After a message has been accepted by a carrier, however, we cannot guarantee that the message will not be queued after this period. We recommend that this value be at least 5 seconds. + :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 Channels Messages. - :param shorten_urls: Determines the usage of Click Tracking. Setting it to `true` will instruct Twilio to replace all links in the Message with a shortened version based on the associated Domain Sid and track clicks on them. If this parameter is not set on an API call, we will use the value set on the Messaging Service. If this parameter is not set and the value is not configured on the Messaging Service used this will default to `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 will deliver the message as a single MMS message, regardless of the presence of media. - :param content_sid: The SID of the Content object returned at Content API content create time (https://www.twilio.com/docs/content-api/create-and-send-your-first-content-api-template#create-a-template). If this parameter is not specified, then the Content API will not be utilized. - :param content_variables: Key-value pairs of variable names to substitution values, used alongside a content_sid. If not specified, Content API will default to the default variables defined at create time. - :param from_: A Twilio phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, an [alphanumeric sender ID](https://www.twilio.com/docs/sms/send-messages#use-an-alphanumeric-sender-id), or a [Channel Endpoint address](https://www.twilio.com/docs/sms/channels#channel-addresses) that is enabled for the type of message you want to send. Phone numbers or [short codes](https://www.twilio.com/docs/sms/api/short-code) purchased from Twilio also work here. You cannot, for example, spoof messages from a private cell phone number. If you are using `messaging_service_sid`, this parameter must be empty. - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/services#send-a-message-with-copilot) you want to associate with the Message. Set this parameter to use the [Messaging Service Settings and Copilot Features](https://www.twilio.com/console/sms/services) you have configured and leave the `from` parameter empty. When only this parameter is set, Twilio will use your enabled Copilot Features to select the `from` phone number for delivery. - :param body: The text of the message you want to send. Can be up to 1,600 characters in length. - :param media_url: The URL of the media to send with the message. The media can be of type `gif`, `png`, and `jpeg` and will be formatted correctly on the recipient's device. The media size limit is 5MB for supported file types (JPEG, PNG, GIF) and 500KB for [other types](https://www.twilio.com/docs/sms/accepted-mime-types) of accepted media. To send more than one image in the message body, provide multiple `media_url` parameters in the POST request. You can include up to 10 `media_url` parameters per message. You can send images in an SMS message in only the US and Canada. + :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 """ - data = values.of( - { - "To": to, - "StatusCallback": status_callback, - "ApplicationSid": application_sid, - "MaxPrice": max_price, - "ProvideFeedback": provide_feedback, - "Attempt": attempt, - "ValidityPeriod": validity_period, - "ForceDelivery": force_delivery, - "ContentRetention": content_retention, - "AddressRetention": address_retention, - "SmartEncoded": smart_encoded, - "PersistentAction": serialize.map(persistent_action, lambda e: e), - "ShortenUrls": shorten_urls, - "ScheduleType": schedule_type, - "SendAt": serialize.iso8601_datetime(send_at), - "SendAsMms": send_as_mms, - "ContentSid": content_sid, - "ContentVariables": content_variables, - "From": from_, - "MessagingServiceSid": messaging_service_sid, - "Body": body, - "MediaUrl": serialize.map(media_url, lambda e: e), - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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: Union[str, object] = values.unset, + 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, - date_sent: Union[datetime, 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, + 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, @@ -668,11 +1277,11 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str to: Read messages sent to only this phone number. - :param str from_: Read messages sent from only this phone number or alphanumeric sender ID. - :param datetime date_sent: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param datetime date_sent_before: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param datetime date_sent_after: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. + :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 @@ -710,11 +1319,11 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str to: Read messages sent to only this phone number. - :param str from_: Read messages sent from only this phone number or alphanumeric sender ID. - :param datetime date_sent: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param datetime date_sent_before: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param datetime date_sent_after: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. + :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 @@ -736,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, @@ -751,11 +1442,11 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str to: Read messages sent to only this phone number. - :param str from_: Read messages sent from only this phone number or alphanumeric sender ID. - :param datetime date_sent: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param datetime date_sent_before: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param datetime date_sent_after: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. + :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 @@ -765,6 +1456,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( to=to, @@ -792,11 +1484,11 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str to: Read messages sent to only this phone number. - :param str from_: Read messages sent from only this phone number or alphanumeric sender ID. - :param datetime date_sent: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param datetime date_sent_before: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param datetime date_sent_after: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. + :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 @@ -806,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( @@ -819,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, @@ -834,11 +1607,11 @@ def page( Retrieve a single page of MessageInstance records from the API. Request is executed immediately - :param to: Read messages sent to only this phone number. - :param from_: Read messages sent from only this phone number or alphanumeric sender ID. - :param date_sent: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param date_sent_before: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param date_sent_after: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. + :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 @@ -858,8 +1631,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MessagePage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -876,11 +1655,11 @@ async def page_async( Asynchronously retrieve a single page of MessageInstance records from the API. Request is executed immediately - :param to: Read messages sent to only this phone number. - :param from_: Read messages sent from only this phone number or alphanumeric sender ID. - :param date_sent: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param date_sent_before: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. - :param date_sent_after: The date of the messages to show. Specify a date as `YYYY-MM-DD` in GMT to read only messages sent on this date. For example: `2009-07-06`. You can also specify an inequality, such as `DateSent<=YYYY-MM-DD`, to read messages sent on or before midnight on a date, and `DateSent>=YYYY-MM-DD` to read messages sent on or after midnight on a date. + :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 @@ -900,10 +1679,114 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MessagePage(self._version, response, self._solution) + 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: """ @@ -915,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: """ @@ -927,13 +1810,13 @@ 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: """ Constructs a MessageContext - :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + :param sid: The SID of the Message resource to be updated """ return MessageContext( self._version, account_sid=self._solution["account_sid"], sid=sid @@ -943,7 +1826,7 @@ def __call__(self, sid: str) -> MessageContext: """ Constructs a MessageContext - :param sid: The Twilio-provided string that uniquely identifies the Message resource to update. + :param sid: The SID of the Message resource to be updated """ return MessageContext( self._version, account_sid=self._solution["account_sid"], sid=sid diff --git a/twilio/rest/api/v2010/account/message/feedback.py b/twilio/rest/api/v2010/account/message/feedback.py index ea7b38ad92..5922ead4e2 100644 --- a/twilio/rest/api/v2010/account/message/feedback.py +++ b/twilio/rest/api/v2010/account/message/feedback.py @@ -12,10 +12,10 @@ 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 @@ -23,16 +23,17 @@ class FeedbackInstance(InstanceResource): + class Outcome(object): CONFIRMED = "confirmed" UNCONFIRMED = "unconfirmed" """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the MessageFeedback resource. - :ivar message_sid: The SID of the Message resource for which the feedback was provided. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this MessageFeedback resource. + :ivar message_sid: The SID of the Message resource associated with this MessageFeedback resource. :ivar outcome: - :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 date_created: The date and time in GMT when this MessageFeedback 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 this MessageFeedback resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar uri: The URI of the resource, relative to `https://api.twilio.com`. """ @@ -72,13 +73,14 @@ def __repr__(self) -> str: class FeedbackList(ListResource): + def __init__(self, version: Version, account_sid: str, message_sid: str): """ Initialize the FeedbackList :param version: Version that contains the resource - :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that will create the resource. - :param message_sid: The SID of the Message resource for which the feedback was provided. + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Message resource for which to create MessageFeedback. + :param message_sid: The SID of the Message resource for which to create MessageFeedback. """ super().__init__(version) @@ -94,28 +96,42 @@ 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 - - :param outcome: + Internal helper for create operation - :returns: The created FeedbackInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Outcome": outcome, } ) + 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, + 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, @@ -123,28 +139,61 @@ 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( { "Outcome": outcome, } ) + 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, + 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, @@ -152,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 33c18d8882..d15bc20f18 100644 --- a/twilio/rest/api/v2010/account/message/media.py +++ b/twilio/rest/api/v2010/account/message/media.py @@ -12,10 +12,10 @@ 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 @@ -24,15 +24,14 @@ class MediaInstance(InstanceResource): - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this Media resource. - :ivar content_type: The default [mime-type](https://en.wikipedia.org/wiki/Internet_media_type) of the media, for example `image/jpeg`, `image/png`, or `image/gif` - :ivar date_created: The date and time in GMT that this 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 this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. - :ivar parent_sid: The SID of the resource that created the media. - :ivar sid: The unique string that that we created to identify this Media resource. - :ivar uri: The URI of this resource, relative to `https://api.twilio.com`. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with this Media resource. + :ivar content_type: The default [MIME type](https://en.wikipedia.org/wiki/Internet_media_type) of the media, for example `image/jpeg`, `image/png`, or `image/gif`. + :ivar date_created: The date and time in GMT when this Media 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 this Media resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :ivar parent_sid: The SID of the Message resource that is associated with this Media resource. + :ivar sid: The unique string that identifies this Media resource. + :ivar uri: The URI of this Media resource, relative to `https://api.twilio.com`. """ def __init__( @@ -62,6 +61,7 @@ def __init__( "message_sid": message_sid, "sid": sid or self.sid, } + self._context: Optional[MediaContext] = None @property @@ -99,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 @@ -117,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 @@ -128,14 +164,15 @@ def __repr__(self) -> str: class MediaContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, message_sid: str, sid: str): """ Initialize the MediaContext :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 Media resource(s) to fetch. - :param message_sid: The SID of the Message resource that this Media resource belongs to. - :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) associated with the Media resource. + :param message_sid: The SID of the Message resource that is associated with the Media resource. + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. """ super().__init__(version) @@ -151,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 @@ -158,9 +209,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -170,9 +243,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MediaInstance 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) -> MediaInstance: @@ -182,19 +279,47 @@ def fetch(self) -> MediaInstance: :returns: The fetched MediaInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], ) - return MediaInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MediaInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MediaInstance: """ @@ -203,19 +328,31 @@ async def fetch_async(self) -> MediaInstance: :returns: The fetched MediaInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MediaInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], ) - return MediaInstance( + 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: """ @@ -228,12 +365,14 @@ def __repr__(self) -> str: class MediaPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MediaInstance: """ Build an instance of MediaInstance :param payload: Payload response from the API """ + return MediaInstance( self._version, payload, @@ -251,13 +390,14 @@ def __repr__(self) -> str: class MediaList(ListResource): + def __init__(self, version: Version, account_sid: str, message_sid: str): """ Initialize the MediaList :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 Media resource(s) to read. - :param message_sid: The SID of the Message resource that this Media resource belongs to. + :param account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that is associated with the Media resources. + :param message_sid: The SID of the Message resource that is associated with the Media resources. """ super().__init__(version) @@ -285,9 +425,9 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param datetime date_created: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param datetime date_created_before: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param datetime date_created_after: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. + :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 @@ -321,9 +461,9 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param datetime date_created: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param datetime date_created_before: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param datetime date_created_after: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. + :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 @@ -343,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, @@ -356,9 +566,9 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param datetime date_created: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param datetime date_created_before: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param datetime date_created_after: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. + :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 @@ -368,6 +578,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -391,9 +602,9 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param datetime date_created: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param datetime date_created_before: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param datetime date_created_after: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. + :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 @@ -403,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( @@ -414,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, @@ -427,9 +707,9 @@ def page( Retrieve a single page of MediaInstance records from the API. Request is executed immediately - :param date_created: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param date_created_before: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param date_created_after: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. + :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 @@ -447,8 +727,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MediaPage(self._version, response, self._solution) + 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 MediaPage(self._version, response, solution=self._solution) async def page_async( self, @@ -463,9 +749,9 @@ async def page_async( Asynchronously retrieve a single page of MediaInstance records from the API. Request is executed immediately - :param date_created: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param date_created_before: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. - :param date_created_after: Only include media that was created on this date. Specify a date as `YYYY-MM-DD` in GMT, for example: `2009-07-06`, to read media that was created on this date. You can also specify an inequality, such as `StartTime<=YYYY-MM-DD`, to read media that was created on or before midnight of this date, and `StartTime>=YYYY-MM-DD` to read media that was created on or after midnight of this date. + :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 @@ -483,10 +769,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MediaPage(self._version, response, self._solution) + 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: """ @@ -498,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: """ @@ -510,13 +888,13 @@ 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: """ Constructs a MediaContext - :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. """ return MediaContext( self._version, @@ -529,7 +907,7 @@ def __call__(self, sid: str) -> MediaContext: """ Constructs a MediaContext - :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch + :param sid: The Twilio-provided string that uniquely identifies the Media resource to fetch. """ return MediaContext( self._version, diff --git a/twilio/rest/api/v2010/account/new_key.py b/twilio/rest/api/v2010/account/new_key.py index e7af236ebe..525891af56 100644 --- a/twilio/rest/api/v2010/account/new_key.py +++ b/twilio/rest/api/v2010/account/new_key.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class NewKeyInstance(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. @@ -60,6 +59,7 @@ def __repr__(self) -> str: class NewKeyList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the NewKeyList @@ -76,6 +76,29 @@ 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + 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 ) -> NewKeyInstance: @@ -86,20 +109,50 @@ def create( :returns: The created NewKeyInstance """ + payload, _, _ = self._create(friendly_name=friendly_name) + return NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return NewKeyInstance( - self._version, payload, account_sid=self._solution["account_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( @@ -112,21 +165,28 @@ async def create_async( :returns: The created NewKeyInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - } + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return NewKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the NewKeyInstance and return response metadata - return NewKeyInstance( + :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: """ diff --git a/twilio/rest/api/v2010/account/new_signing_key.py b/twilio/rest/api/v2010/account/new_signing_key.py index d24e833b86..ebbb680958 100644 --- a/twilio/rest/api/v2010/account/new_signing_key.py +++ b/twilio/rest/api/v2010/account/new_signing_key.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class NewSigningKeyInstance(InstanceResource): - """ :ivar sid: The unique string that that we created to identify the NewSigningKey resource. :ivar friendly_name: The string that you assigned to describe the resource. @@ -60,6 +59,7 @@ def __repr__(self) -> str: class NewSigningKeyList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the NewSigningKeyList @@ -76,6 +76,29 @@ 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + 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 ) -> NewSigningKeyInstance: @@ -86,20 +109,50 @@ def create( :returns: The created NewSigningKeyInstance """ + payload, _, _ = self._create(friendly_name=friendly_name) + return NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] + ) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return NewSigningKeyInstance( - self._version, payload, account_sid=self._solution["account_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( @@ -112,21 +165,28 @@ async def create_async( :returns: The created NewSigningKeyInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - } + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return NewSigningKeyInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the NewSigningKeyInstance and return response metadata - return NewSigningKeyInstance( + :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: """ diff --git a/twilio/rest/api/v2010/account/notification.py b/twilio/rest/api/v2010/account/notification.py index 69e647cd4a..9afbd26354 100644 --- a/twilio/rest/api/v2010/account/notification.py +++ b/twilio/rest/api/v2010/account/notification.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,7 +24,6 @@ class NotificationInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Notification resource. :ivar api_version: The API version used to generate the notification. Can be empty for events that don't have a specific API version, such as incoming phone calls. @@ -82,6 +81,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[NotificationContext] = None @property @@ -118,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 @@ -129,6 +147,7 @@ def __repr__(self) -> str: class NotificationContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the NotificationContext @@ -148,6 +167,22 @@ def __init__(self, version: Version, account_sid: str, sid: str): **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) -> NotificationInstance: """ Fetch the NotificationInstance @@ -155,18 +190,45 @@ def fetch(self) -> NotificationInstance: :returns: The fetched NotificationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return NotificationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> NotificationInstance: """ @@ -175,18 +237,29 @@ async def fetch_async(self) -> NotificationInstance: :returns: The fetched NotificationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return NotificationInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return NotificationInstance( + 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: """ @@ -199,12 +272,14 @@ def __repr__(self) -> str: class NotificationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> NotificationInstance: """ Build an instance of NotificationInstance :param payload: Payload response from the API """ + return NotificationInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -219,6 +294,7 @@ def __repr__(self) -> str: class NotificationList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the NotificationList @@ -315,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, @@ -342,6 +494,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( log=log, @@ -380,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( @@ -392,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, @@ -428,8 +656,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return NotificationPage(self._version, response, self._solution) + 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 NotificationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -467,10 +701,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return NotificationPage(self._version, response, self._solution) + 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: """ @@ -482,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: """ @@ -494,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 90d5e472e4..16f29c6f7d 100644 --- a/twilio/rest/api/v2010/account/outgoing_caller_id.py +++ b/twilio/rest/api/v2010/account/outgoing_caller_id.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class OutgoingCallerIdInstance(InstanceResource): - """ :ivar sid: The unique string that that we created to identify the OutgoingCallerId 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. @@ -60,6 +59,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[OutgoingCallerIdContext] = None @property @@ -96,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 @@ -114,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": @@ -142,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 @@ -153,6 +217,7 @@ def __repr__(self) -> str: class OutgoingCallerIdContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the OutgoingCallerIdContext @@ -172,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 @@ -179,9 +258,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -191,9 +292,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OutgoingCallerIdInstance 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) -> OutgoingCallerIdInstance: @@ -203,18 +328,45 @@ def fetch(self) -> OutgoingCallerIdInstance: :returns: The fetched OutgoingCallerIdInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return OutgoingCallerIdInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return OutgoingCallerIdInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OutgoingCallerIdInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> OutgoingCallerIdInstance: """ @@ -223,12 +375,7 @@ async def fetch_async(self) -> OutgoingCallerIdInstance: :returns: The fetched OutgoingCallerIdInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return OutgoingCallerIdInstance( self._version, payload, @@ -236,28 +383,56 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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 + ) -> 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, @@ -265,28 +440,61 @@ 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( { "FriendlyName": friendly_name, } ) + 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, + 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, @@ -294,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 @@ -305,12 +534,14 @@ def __repr__(self) -> str: class OutgoingCallerIdPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> OutgoingCallerIdInstance: """ Build an instance of OutgoingCallerIdInstance :param payload: Payload response from the API """ + return OutgoingCallerIdInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -325,6 +556,7 @@ def __repr__(self) -> str: class OutgoingCallerIdList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the OutgoingCallerIdList @@ -409,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, @@ -432,6 +728,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( phone_number=phone_number, @@ -464,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( @@ -474,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, @@ -504,8 +864,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return OutgoingCallerIdPage(self._version, response, self._solution) + 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 OutgoingCallerIdPage(self._version, response, solution=self._solution) async def page_async( self, @@ -537,10 +903,96 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return OutgoingCallerIdPage(self._version, response, self._solution) + 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: """ @@ -552,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: """ @@ -564,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 73589708fb..dd8ca881f9 100644 --- a/twilio/rest/api/v2010/account/queue/__init__.py +++ b/twilio/rest/api/v2010/account/queue/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class QueueInstance(InstanceResource): - """ :ivar date_updated: The date and time in GMT that this resource was last updated, specified in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. :ivar current_size: The number of calls currently in the queue. @@ -69,6 +68,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[QueueContext] = None @property @@ -105,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 @@ -123,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, @@ -159,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: """ @@ -177,6 +249,7 @@ def __repr__(self) -> str: class QueueContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the QueueContext @@ -196,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 @@ -203,9 +290,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -215,9 +324,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the QueueInstance 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) -> QueueInstance: @@ -227,18 +360,45 @@ def fetch(self) -> QueueInstance: :returns: The fetched QueueInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return QueueInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the QueueInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> QueueInstance: """ @@ -247,45 +407,72 @@ async def fetch_async(self) -> QueueInstance: :returns: The fetched QueueInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return QueueInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return QueueInstance( + 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( + 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( { "FriendlyName": friendly_name, "MaxSize": max_size, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -293,32 +480,74 @@ 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( { "FriendlyName": friendly_name, "MaxSize": max_size, } ) + 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, + 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, @@ -326,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: """ @@ -350,12 +603,14 @@ def __repr__(self) -> str: class QueuePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> QueueInstance: """ Build an instance of QueueInstance :param payload: Payload response from the API """ + return QueueInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -370,6 +625,7 @@ def __repr__(self) -> str: class QueueList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the QueueList @@ -386,6 +642,32 @@ def __init__(self, version: Version, account_sid: str): } self._uri = "/Accounts/{account_sid}/Queues.json".format(**self._solution) + def _create( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "MaxSize": max_size, + } + ) + 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, max_size: Union[int, object] = values.unset ) -> QueueInstance: @@ -397,21 +679,54 @@ def create( :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"] + ) + + def create_with_http_info( + self, friendly_name: str, max_size: Union[int, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, "MaxSize": max_size, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return QueueInstance( - self._version, payload, account_sid=self._solution["account_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( @@ -425,22 +740,31 @@ async def create_async( :returns: The created QueueInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "MaxSize": max_size, - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, max_size=max_size ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return QueueInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return QueueInstance( + 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, @@ -492,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, @@ -511,6 +885,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -537,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( @@ -545,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, @@ -569,8 +995,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return QueuePage(self._version, response, self._solution) + 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 QueuePage(self._version, response, solution=self._solution) async def page_async( self, @@ -596,10 +1028,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return QueuePage(self._version, response, self._solution) + 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: """ @@ -611,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: """ @@ -623,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 842a178953..540befbbbe 100644 --- a/twilio/rest/api/v2010/account/queue/member.py +++ b/twilio/rest/api/v2010/account/queue/member.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class MemberInstance(InstanceResource): - """ :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Member resource is associated with. :ivar date_enqueued: The date that the member was enqueued, given in RFC 2822 format. @@ -58,6 +57,7 @@ def __init__( "queue_sid": queue_sid, "call_sid": call_sid or self.call_sid, } + self._context: Optional[MemberContext] = None @property @@ -95,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": @@ -127,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 @@ -138,6 +188,7 @@ def __repr__(self) -> str: class MemberContext(InstanceContext): + def __init__( self, version: Version, account_sid: str, queue_sid: str, call_sid: str ): @@ -163,6 +214,22 @@ def __init__( ) ) + 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) -> MemberInstance: """ Fetch the MemberInstance @@ -170,19 +237,47 @@ def fetch(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MemberInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + queue_sid=self._solution["queue_sid"], + call_sid=self._solution["call_sid"], ) - return MemberInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MemberInstance: """ @@ -191,12 +286,7 @@ async def fetch_async(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return MemberInstance( self._version, payload, @@ -205,30 +295,59 @@ 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( { "Url": url, "Method": method, } ) + 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, + 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, @@ -237,30 +356,65 @@ 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( { "Url": url, "Method": method, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -269,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 @@ -280,12 +455,14 @@ def __repr__(self) -> str: class MemberPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: """ Build an instance of MemberInstance :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -303,6 +480,7 @@ def __repr__(self) -> str: class MemberList(ListResource): + def __init__(self, version: Version, account_sid: str, queue_sid: str): """ Initialize the MemberList @@ -373,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, @@ -392,6 +620,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -418,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( @@ -426,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, @@ -450,8 +730,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MemberPage(self._version, response, self._solution) + 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 MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -477,10 +763,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MemberPage(self._version, response, self._solution) + 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: """ @@ -492,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: """ @@ -504,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 10ee3e1b90..75af476b00 100644 --- a/twilio/rest/api/v2010/account/recording/__init__.py +++ b/twilio/rest/api/v2010/account/recording/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,6 +26,7 @@ class RecordingInstance(InstanceResource): + class Source(object): DIALVERB = "DialVerb" CONFERENCE = "Conference" @@ -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`. You can split a call with two legs into two separate recording channels if you record using [TwiML Dial](https://www.twilio.com/docs/voice/twiml/dial#record) or the [Outbound Rest API](https://www.twilio.com/docs/voice/make-calls#manage-your-outbound-call). + :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: """ @@ -198,6 +246,7 @@ def __repr__(self) -> str: class RecordingContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the RecordingContext @@ -220,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 @@ -227,9 +290,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -239,9 +324,39 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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, include_soft_deleted: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), + } + ) + + 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( @@ -254,21 +369,58 @@ def fetch( :returns: The fetched RecordingInstance """ - - data = values.of( - { - "IncludeSoftDeleted": include_soft_deleted, - } + payload, _, _ = self._fetch(include_soft_deleted=include_soft_deleted) + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + def fetch_with_http_info( + self, include_soft_deleted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Fetch the RecordingInstance and return response metadata - return 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: 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) + + 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), + } + ) + + 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_soft_deleted: Union[bool, object] = values.unset @@ -280,23 +432,36 @@ async def fetch_async( :returns: The fetched RecordingInstance """ - - data = values.of( - { - "IncludeSoftDeleted": include_soft_deleted, - } + payload, _, _ = await self._fetch_async( + include_soft_deleted=include_soft_deleted ) - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + return RecordingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return RecordingInstance( + 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: @@ -335,12 +500,14 @@ def __repr__(self) -> str: class RecordingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: """ Build an instance of RecordingInstance :param payload: Payload response from the API """ + return RecordingInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -355,6 +522,7 @@ def __repr__(self) -> str: class RecordingList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the RecordingList @@ -461,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, @@ -492,6 +748,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created=date_created, @@ -536,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( @@ -550,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, @@ -585,15 +929,21 @@ def page( "DateCreated>": serialize.iso8601_datetime(date_created_after), "CallSid": call_sid, "ConferenceSid": conference_sid, - "IncludeSoftDeleted": include_soft_deleted, + "IncludeSoftDeleted": serialize.boolean_to_string(include_soft_deleted), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RecordingPage(self._version, response, self._solution) + 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 RecordingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -630,17 +980,127 @@ async def page_async( "DateCreated>": serialize.iso8601_datetime(date_created_after), "CallSid": call_sid, "ConferenceSid": conference_sid, - "IncludeSoftDeleted": include_soft_deleted, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RecordingPage(self._version, response, self._solution) + 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: """ @@ -652,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: """ @@ -664,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 79d3a71365..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 @@ -12,10 +12,10 @@ 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 @@ -25,6 +25,7 @@ class AddOnResultInstance(InstanceResource): + class Status(object): CANCELED = "canceled" COMPLETED = "completed" @@ -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: """ @@ -157,6 +195,7 @@ def __repr__(self) -> str: class AddOnResultContext(InstanceContext): + def __init__( self, version: Version, account_sid: str, reference_sid: str, sid: str ): @@ -182,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 @@ -189,9 +242,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -201,9 +276,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddOnResultInstance 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) -> AddOnResultInstance: @@ -213,19 +312,47 @@ def fetch(self) -> AddOnResultInstance: :returns: The fetched AddOnResultInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], ) - return AddOnResultInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddOnResultInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AddOnResultInstance: """ @@ -234,19 +361,31 @@ async def fetch_async(self) -> AddOnResultInstance: :returns: The fetched AddOnResultInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AddOnResultInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + reference_sid=self._solution["reference_sid"], + sid=self._solution["sid"], ) - return AddOnResultInstance( + 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: @@ -273,12 +412,14 @@ def __repr__(self) -> str: class AddOnResultPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AddOnResultInstance: """ Build an instance of AddOnResultInstance :param payload: Payload response from the API """ + return AddOnResultInstance( self._version, payload, @@ -296,6 +437,7 @@ def __repr__(self) -> str: class AddOnResultList(ListResource): + def __init__(self, version: Version, account_sid: str, reference_sid: str): """ Initialize the AddOnResultList @@ -366,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, @@ -385,6 +577,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -411,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( @@ -419,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, @@ -443,8 +687,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AddOnResultPage(self._version, response, self._solution) + 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 AddOnResultPage(self._version, response, solution=self._solution) async def page_async( self, @@ -470,10 +720,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return AddOnResultPage(self._version, response, self._solution) + 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: """ @@ -485,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: """ @@ -497,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.py b/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py similarity index 57% rename from twilio/rest/api/v2010/account/recording/add_on_result/payload.py rename to twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py index 08e8822202..cabc10f323 100644 --- a/twilio/rest/api/v2010/account/recording/add_on_result/payload.py +++ b/twilio/rest/api/v2010/account/recording/add_on_result/payload/__init__.py @@ -12,19 +12,19 @@ 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 +from twilio.rest.api.v2010.account.recording.add_on_result.payload.data import DataList class PayloadInstance(InstanceResource): - """ :ivar sid: The unique string that that we created to identify the Recording AddOnResult Payload resource. :ivar add_on_result_sid: The SID of the AddOnResult to which the payload belongs. @@ -76,6 +76,7 @@ def __init__( "add_on_result_sid": add_on_result_sid, "sid": sid or self.sid, } + self._context: Optional[PayloadContext] = None @property @@ -114,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 @@ -132,6 +151,31 @@ 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: + """ + Access the data + """ + return self._proxy.data + def __repr__(self) -> str: """ Provide a friendly representation @@ -143,6 +187,7 @@ def __repr__(self) -> str: class PayloadContext(InstanceContext): + def __init__( self, version: Version, @@ -173,6 +218,22 @@ def __init__( **self._solution ) + 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 @@ -180,9 +241,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -192,9 +275,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PayloadInstance 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) -> PayloadInstance: @@ -204,13 +311,25 @@ def fetch(self) -> PayloadInstance: :returns: The fetched PayloadInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return 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 PayloadInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PayloadInstance and return response metadata + + + :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"], @@ -218,6 +337,23 @@ def fetch(self) -> PayloadInstance: 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> PayloadInstance: """ @@ -226,13 +362,25 @@ async def fetch_async(self) -> PayloadInstance: :returns: The fetched PayloadInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return 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 PayloadInstance( + 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"], @@ -240,6 +388,22 @@ async def fetch_async(self) -> PayloadInstance: 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: + """ + Access the data + """ + if self._data is None: + self._data = DataList( + self._version, + self._solution["account_sid"], + self._solution["reference_sid"], + self._solution["add_on_result_sid"], + self._solution["sid"], + ) + return self._data def __repr__(self) -> str: """ @@ -252,12 +416,14 @@ def __repr__(self) -> str: class PayloadPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> PayloadInstance: """ Build an instance of PayloadInstance :param payload: Payload response from the API """ + return PayloadInstance( self._version, payload, @@ -276,6 +442,7 @@ def __repr__(self) -> str: class PayloadList(ListResource): + def __init__( self, version: Version, @@ -354,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, @@ -373,6 +590,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -399,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( @@ -407,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, @@ -431,8 +700,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return PayloadPage(self._version, response, self._solution) + 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 PayloadPage(self._version, response, solution=self._solution) async def page_async( self, @@ -458,10 +733,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return PayloadPage(self._version, response, self._solution) + 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: """ @@ -473,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: """ @@ -485,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 new file mode 100644 index 0000000000..e0847813c0 --- /dev/null +++ b/twilio/rest/api/v2010/account/recording/add_on_result/payload/data.py @@ -0,0 +1,321 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Api + 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 DataInstance(InstanceResource): + """ + :ivar redirect_to: The URL to redirect to to get the data returned by the AddOn that was previously stored. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + payload_sid: str, + ): + super().__init__(version) + + self.redirect_to: Optional[str] = payload.get("redirect_to") + + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "payload_sid": payload_sid, + } + + self._context: Optional[DataContext] = None + + @property + def _proxy(self) -> "DataContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: DataContext for this DataInstance + """ + if self._context is None: + self._context = DataContext( + self._version, + 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 self._context + + def fetch(self) -> "DataInstance": + """ + Fetch the DataInstance + + + :returns: The fetched DataInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "DataInstance": + """ + Asynchronous coroutine to fetch the DataInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DataContext(InstanceContext): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + payload_sid: str, + ): + """ + Initialize the DataContext + + :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 Recording AddOnResult Payload resource to fetch. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload to fetch belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payload to fetch belongs. + :param payload_sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "payload_sid": payload_sid, + } + self._uri = "/Accounts/{account_sid}/Recordings/{reference_sid}/AddOnResults/{add_on_result_sid}/Payloads/{payload_sid}/Data.json".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) -> DataInstance: + """ + Fetch the DataInstance + + + :returns: The fetched DataInstance + """ + payload, _, _ = self._fetch() + return 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"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DataInstance and return response metadata + + + :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" + + 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, + 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"], + ) + + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class DataList(ListResource): + + def __init__( + self, + version: Version, + account_sid: str, + reference_sid: str, + add_on_result_sid: str, + payload_sid: str, + ): + """ + Initialize the DataList + + :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 Recording AddOnResult Payload resource to fetch. + :param reference_sid: The SID of the recording to which the AddOnResult resource that contains the payload to fetch belongs. + :param add_on_result_sid: The SID of the AddOnResult to which the payload to fetch belongs. + :param payload_sid: The Twilio-provided string that uniquely identifies the Recording AddOnResult Payload resource to fetch. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "account_sid": account_sid, + "reference_sid": reference_sid, + "add_on_result_sid": add_on_result_sid, + "payload_sid": payload_sid, + } + + def get(self) -> DataContext: + """ + Constructs a DataContext + + """ + return DataContext( + self._version, + 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"], + ) + + def __call__(self) -> DataContext: + """ + Constructs a DataContext + + """ + return DataContext( + self._version, + 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"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/api/v2010/account/recording/transcription.py b/twilio/rest/api/v2010/account/recording/transcription.py index 6aa104d427..166d49f641 100644 --- a/twilio/rest/api/v2010/account/recording/transcription.py +++ b/twilio/rest/api/v2010/account/recording/transcription.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class TranscriptionInstance(InstanceResource): + class Status(object): IN_PROGRESS = "in-progress" COMPLETED = "completed" @@ -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 @@ -144,6 +182,7 @@ def __repr__(self) -> str: class TranscriptionContext(InstanceContext): + def __init__( self, version: Version, account_sid: str, recording_sid: str, sid: str ): @@ -167,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 @@ -174,9 +227,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -186,9 +261,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -198,19 +297,47 @@ def fetch(self) -> TranscriptionInstance: :returns: The fetched TranscriptionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], ) - return TranscriptionInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TranscriptionInstance: """ @@ -219,19 +346,31 @@ async def fetch_async(self) -> TranscriptionInstance: :returns: The fetched TranscriptionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + recording_sid=self._solution["recording_sid"], + sid=self._solution["sid"], ) - return TranscriptionInstance( + 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: """ @@ -244,12 +383,14 @@ def __repr__(self) -> str: class TranscriptionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: """ Build an instance of TranscriptionInstance :param payload: Payload response from the API """ + return TranscriptionInstance( self._version, payload, @@ -267,6 +408,7 @@ def __repr__(self) -> str: class TranscriptionList(ListResource): + def __init__(self, version: Version, account_sid: str, recording_sid: str): """ Initialize the TranscriptionList @@ -337,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, @@ -356,6 +548,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -382,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( @@ -390,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, @@ -414,8 +658,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TranscriptionPage(self._version, response, self._solution) + 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 TranscriptionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -441,10 +691,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return TranscriptionPage(self._version, response, self._solution) + 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: """ @@ -456,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: """ @@ -468,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 831cb770af..c1c2e3f689 100644 --- a/twilio/rest/api/v2010/account/short_code.py +++ b/twilio/rest/api/v2010/account/short_code.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class ShortCodeInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this ShortCode resource. :ivar api_version: The API version used to start a new TwiML session when an SMS message is sent to this short code. @@ -70,6 +69,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[ShortCodeContext] = None @property @@ -106,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, @@ -166,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 @@ -177,6 +255,7 @@ def __repr__(self) -> str: class ShortCodeContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the ShortCodeContext @@ -196,6 +275,22 @@ def __init__(self, version: Version, account_sid: str, sid: str): **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) -> ShortCodeInstance: """ Fetch the ShortCodeInstance @@ -203,18 +298,45 @@ def fetch(self) -> ShortCodeInstance: :returns: The fetched ShortCodeInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return ShortCodeInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ShortCodeInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ShortCodeInstance: """ @@ -223,20 +345,31 @@ async def fetch_async(self) -> ShortCodeInstance: :returns: The fetched ShortCodeInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ShortCodeInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return ShortCodeInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, api_version: Union[str, object] = values.unset, @@ -244,19 +377,14 @@ 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( { "FriendlyName": friendly_name, @@ -267,13 +395,45 @@ def update( "SmsFallbackMethod": sms_fallback_method, } ) + 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, + 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, @@ -281,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, @@ -289,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`. @@ -300,8 +460,40 @@ 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( { "FriendlyName": friendly_name, @@ -312,13 +504,45 @@ async def update_async( "SmsFallbackMethod": sms_fallback_method, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -326,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 @@ -337,12 +598,14 @@ def __repr__(self) -> str: 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, account_sid=self._solution["account_sid"] ) @@ -357,6 +620,7 @@ def __repr__(self) -> str: class ShortCodeList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the ShortCodeList @@ -441,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, @@ -464,6 +792,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -496,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( @@ -506,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, @@ -536,8 +928,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ShortCodePage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -569,10 +967,96 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ShortCodePage(self._version, response, self._solution) + 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: """ @@ -584,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: """ @@ -596,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 e14f42c777..64ba733192 100644 --- a/twilio/rest/api/v2010/account/signing_key.py +++ b/twilio/rest/api/v2010/account/signing_key.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class SigningKeyInstance(InstanceResource): - """ :ivar sid: :ivar friendly_name: @@ -54,6 +53,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[SigningKeyContext] = None @property @@ -90,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 @@ -108,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": @@ -136,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 @@ -147,6 +211,7 @@ def __repr__(self) -> str: class SigningKeyContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the SigningKeyContext @@ -166,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 @@ -173,9 +252,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -185,9 +286,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SigningKeyInstance 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) -> SigningKeyInstance: @@ -197,18 +322,45 @@ def fetch(self) -> SigningKeyInstance: :returns: The fetched SigningKeyInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SigningKeyInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return SigningKeyInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SigningKeyInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SigningKeyInstance: """ @@ -217,12 +369,7 @@ async def fetch_async(self) -> SigningKeyInstance: :returns: The fetched SigningKeyInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return SigningKeyInstance( self._version, payload, @@ -230,28 +377,56 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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 + ) -> SigningKeyInstance: + """ + Update the SigningKeyInstance + + :param friendly_name: + + :returns: The updated SigningKeyInstance + """ + payload, _, _ = self._update(friendly_name=friendly_name) return SigningKeyInstance( self._version, payload, @@ -259,28 +434,61 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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 + ) -> 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, @@ -288,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 @@ -299,12 +528,14 @@ def __repr__(self) -> str: class SigningKeyPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SigningKeyInstance: """ Build an instance of SigningKeyInstance :param payload: Payload response from the API """ + return SigningKeyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -319,6 +550,7 @@ def __repr__(self) -> str: class SigningKeyList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the SigningKeyList @@ -385,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, @@ -404,6 +686,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -430,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( @@ -438,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, @@ -462,8 +796,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SigningKeyPage(self._version, response, self._solution) + 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 SigningKeyPage(self._version, response, solution=self._solution) async def page_async( self, @@ -489,10 +829,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SigningKeyPage(self._version, response, self._solution) + 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: """ @@ -504,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: """ @@ -516,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/__init__.py b/twilio/rest/api/v2010/account/sip/__init__.py index a0780cb1e4..12c695ff72 100644 --- a/twilio/rest/api/v2010/account/sip/__init__.py +++ b/twilio/rest/api/v2010/account/sip/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -27,6 +26,7 @@ class SipList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the SipList 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 08ac5bcfe6..0aef74f3b0 100644 --- a/twilio/rest/api/v2010/account/sip/credential_list/__init__.py +++ b/twilio/rest/api/v2010/account/sip/credential_list/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class CredentialListInstance(InstanceResource): - """ :ivar account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) that owns this resource. :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. @@ -63,6 +62,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialListContext] = None @property @@ -99,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 @@ -117,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 @@ -141,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: """ @@ -159,6 +219,7 @@ def __repr__(self) -> str: class CredentialListContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the CredentialListContext @@ -180,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 @@ -187,9 +262,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -199,9 +296,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance 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) -> CredentialListInstance: @@ -211,18 +332,45 @@ def fetch(self) -> CredentialListInstance: :returns: The fetched CredentialListInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return CredentialListInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialListInstance: """ @@ -231,12 +379,7 @@ async def fetch_async(self) -> CredentialListInstance: :returns: The fetched CredentialListInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return CredentialListInstance( self._version, payload, @@ -244,26 +387,54 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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: 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, @@ -271,26 +442,55 @@ 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( { "FriendlyName": friendly_name, } ) + 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, + 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, @@ -298,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: """ @@ -322,12 +541,14 @@ def __repr__(self) -> str: class CredentialListPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: """ Build an instance of CredentialListInstance :param payload: Payload response from the API """ + return CredentialListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -342,6 +563,7 @@ def __repr__(self) -> str: class CredentialListList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the CredentialListList @@ -360,54 +582,108 @@ 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 + Internal helper for create operation - :param friendly_name: A human readable descriptive text that describes the CredentialList, up to 64 characters long. - - :returns: The created CredentialListInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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) -> 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( { "FriendlyName": friendly_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, + 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, @@ -458,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, @@ -477,6 +803,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -503,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( @@ -511,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, @@ -535,8 +913,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return CredentialListPage(self._version, response, self._solution) + 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 CredentialListPage(self._version, response, solution=self._solution) async def page_async( self, @@ -562,10 +946,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return CredentialListPage(self._version, response, self._solution) + 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: """ @@ -577,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: """ @@ -589,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 585950c25c..2a237527f2 100644 --- a/twilio/rest/api/v2010/account/sip/credential_list/credential.py +++ b/twilio/rest/api/v2010/account/sip/credential_list/credential.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class CredentialInstance(InstanceResource): - """ :ivar sid: A 34 character string that uniquely identifies this resource. :ivar account_sid: The unique id of the Account that is responsible for this resource. @@ -62,6 +61,7 @@ def __init__( "credential_list_sid": credential_list_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialContext] = None @property @@ -99,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 @@ -117,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": @@ -145,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 @@ -156,6 +220,7 @@ def __repr__(self) -> str: class CredentialContext(InstanceContext): + def __init__( self, version: Version, account_sid: str, credential_list_sid: str, sid: str ): @@ -179,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 @@ -186,9 +265,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -198,9 +299,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance 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) -> CredentialInstance: @@ -210,19 +335,47 @@ def fetch(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + credential_list_sid=self._solution["credential_list_sid"], + sid=self._solution["sid"], ) - return CredentialInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialInstance: """ @@ -231,12 +384,7 @@ async def fetch_async(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return CredentialInstance( self._version, payload, @@ -245,26 +393,55 @@ 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( { "Password": password, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -273,28 +450,60 @@ 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( { "Password": password, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -303,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 @@ -314,12 +543,14 @@ def __repr__(self) -> str: 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, @@ -337,6 +568,7 @@ def __repr__(self) -> str: class CredentialList(ListResource): + def __init__(self, version: Version, account_sid: str, credential_list_sid: str): """ Initialize the CredentialList @@ -357,28 +589,40 @@ 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( { "Username": username, "Password": password, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -386,28 +630,60 @@ 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( { "Username": username, "Password": password, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -415,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, @@ -465,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, @@ -484,6 +832,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -510,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( @@ -518,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, @@ -542,8 +942,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return CredentialPage(self._version, response, self._solution) + 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 CredentialPage(self._version, response, solution=self._solution) async def page_async( self, @@ -569,10 +975,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return CredentialPage(self._version, response, self._solution) + 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: """ @@ -584,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: """ @@ -596,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 29a2aaeb2a..3b8f3f32e9 100644 --- a/twilio/rest/api/v2010/account/sip/domain/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/__init__.py @@ -12,10 +12,10 @@ 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 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,7 +31,6 @@ class DomainInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the SipDomain resource. :ivar api_version: The API version used to process the call. @@ -103,6 +102,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[DomainContext] = None @property @@ -139,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 @@ -157,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, @@ -259,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: """ @@ -291,6 +429,7 @@ def __repr__(self) -> str: class DomainContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the DomainContext @@ -316,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 @@ -323,9 +476,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -335,9 +510,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainInstance 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) -> DomainInstance: @@ -347,18 +546,45 @@ def fetch(self) -> DomainInstance: :returns: The fetched DomainInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return DomainInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> DomainInstance: """ @@ -367,20 +593,31 @@ async def fetch_async(self) -> DomainInstance: :returns: The fetched DomainInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return DomainInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return DomainInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, voice_fallback_method: Union[str, object] = values.unset, @@ -395,26 +632,14 @@ 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( { "FriendlyName": friendly_name, @@ -424,29 +649,27 @@ def update( "VoiceStatusCallbackMethod": voice_status_callback_method, "VoiceStatusCallbackUrl": voice_status_callback_url, "VoiceUrl": voice_url, - "SipRegistration": sip_registration, + "SipRegistration": serialize.boolean_to_string(sip_registration), "DomainName": domain_name, - "EmergencyCallingEnabled": emergency_calling_enabled, - "Secure": secure, + "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({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return DomainInstance( - self._version, - payload, - account_sid=self._solution["account_sid"], - sid=self._solution["sid"], + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, voice_fallback_method: Union[str, object] = values.unset, @@ -463,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`. @@ -481,30 +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": sip_registration, - "DomainName": domain_name, - "EmergencyCallingEnabled": emergency_calling_enabled, - "Secure": secure, - "ByocTrunkSid": byoc_trunk_sid, - "EmergencyCallerSid": emergency_caller_sid, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, @@ -512,14 +726,239 @@ async def update_async( sid=self._solution["sid"], ) - @property - def auth(self) -> AuthTypesList: - """ - Access the auth + 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: """ - if self._auth is None: - self._auth = AuthTypesList( - self._version, + 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"], ) @@ -562,12 +1001,14 @@ def __repr__(self) -> str: class DomainPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> DomainInstance: """ Build an instance of DomainInstance :param payload: Payload response from the API """ + return DomainInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -582,6 +1023,7 @@ def __repr__(self) -> str: class DomainList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the DomainList @@ -598,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, @@ -613,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. @@ -631,8 +1179,51 @@ 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( { "DomainName": domain_name, @@ -643,22 +1234,23 @@ def create( "VoiceFallbackMethod": voice_fallback_method, "VoiceStatusCallbackUrl": voice_status_callback_url, "VoiceStatusCallbackMethod": voice_status_callback_method, - "SipRegistration": sip_registration, - "EmergencyCallingEnabled": emergency_calling_enabled, - "Secure": secure, + "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"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return DomainInstance( - self._version, payload, account_sid=self._solution["account_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( @@ -696,33 +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": sip_registration, - "EmergencyCallingEnabled": emergency_calling_enabled, - "Secure": 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return DomainInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return DomainInstance( + 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 + + :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: 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, + ) + instance = DomainInstance( self._version, payload, account_sid=self._solution["account_sid"] ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -774,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, @@ -793,6 +1481,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -819,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( @@ -827,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, @@ -851,8 +1591,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DomainPage(self._version, response, self._solution) + 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 DomainPage(self._version, response, solution=self._solution) async def page_async( self, @@ -878,10 +1624,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return DomainPage(self._version, response, self._solution) + 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: """ @@ -893,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: """ @@ -905,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/__init__.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py index 282d3b64e5..73a81ac90d 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -28,6 +27,7 @@ class AuthTypesList(ListResource): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ Initialize the AuthTypesList diff --git a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py index 9d822b4fe9..79a42fa01d 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_calls/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -28,6 +27,7 @@ class AuthTypeCallsList(ListResource): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ Initialize the AuthTypeCallsList @@ -50,9 +50,9 @@ def __init__(self, version: Version, account_sid: str, domain_sid: str): ) ) - self._credential_list_mappings: Optional[ - AuthCallsCredentialListMappingList - ] = None + self._credential_list_mappings: Optional[AuthCallsCredentialListMappingList] = ( + None + ) self._ip_access_control_list_mappings: Optional[ AuthCallsIpAccessControlListMappingList ] = None 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 c9cade64f9..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class AuthCallsCredentialListMappingInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping 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. @@ -58,6 +57,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[AuthCallsCredentialListMappingContext] = None @property @@ -95,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 @@ -113,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 @@ -126,6 +162,7 @@ def __repr__(self) -> str: class AuthCallsCredentialListMappingContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): """ Initialize the AuthCallsCredentialListMappingContext @@ -147,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 @@ -154,9 +205,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -166,9 +239,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsCredentialListMappingInstance 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) -> AuthCallsCredentialListMappingInstance: @@ -178,19 +275,47 @@ def fetch(self) -> AuthCallsCredentialListMappingInstance: :returns: The fetched AuthCallsCredentialListMappingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return AuthCallsCredentialListMappingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsCredentialListMappingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AuthCallsCredentialListMappingInstance: """ @@ -199,19 +324,31 @@ async def fetch_async(self) -> AuthCallsCredentialListMappingInstance: :returns: The fetched AuthCallsCredentialListMappingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AuthCallsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return AuthCallsCredentialListMappingInstance( + 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: """ @@ -226,6 +363,7 @@ def __repr__(self) -> str: class AuthCallsCredentialListMappingPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> AuthCallsCredentialListMappingInstance: @@ -234,6 +372,7 @@ def get_instance( :param payload: Payload response from the API """ + return AuthCallsCredentialListMappingInstance( self._version, payload, @@ -251,6 +390,7 @@ def __repr__(self) -> str: class AuthCallsCredentialListMappingList(ListResource): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ Initialize the AuthCallsCredentialListMappingList @@ -271,28 +411,40 @@ 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 - - :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + Internal helper for create operation - :returns: The created AuthCallsCredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "CredentialListSid": credential_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -300,28 +452,61 @@ 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( { "CredentialListSid": credential_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -329,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, @@ -379,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, @@ -398,6 +654,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -424,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( @@ -432,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, @@ -456,9 +764,15 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 AuthCallsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -485,12 +799,90 @@ async def page_async( } ) + 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 + 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: """ @@ -503,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( @@ -519,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 f83393c377..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class AuthCallsIpAccessControlListMappingInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlListMapping 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. @@ -58,6 +57,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[AuthCallsIpAccessControlListMappingContext] = None @property @@ -95,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 @@ -113,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 @@ -128,6 +164,7 @@ def __repr__(self) -> str: class AuthCallsIpAccessControlListMappingContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): """ Initialize the AuthCallsIpAccessControlListMappingContext @@ -149,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 @@ -156,9 +207,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -168,9 +241,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthCallsIpAccessControlListMappingInstance 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) -> AuthCallsIpAccessControlListMappingInstance: @@ -180,19 +277,47 @@ def fetch(self) -> AuthCallsIpAccessControlListMappingInstance: :returns: The fetched AuthCallsIpAccessControlListMappingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return AuthCallsIpAccessControlListMappingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthCallsIpAccessControlListMappingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AuthCallsIpAccessControlListMappingInstance: """ @@ -201,19 +326,31 @@ async def fetch_async(self) -> AuthCallsIpAccessControlListMappingInstance: :returns: The fetched AuthCallsIpAccessControlListMappingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AuthCallsIpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return AuthCallsIpAccessControlListMappingInstance( + 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: """ @@ -230,6 +367,7 @@ def __repr__(self) -> str: class AuthCallsIpAccessControlListMappingPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> AuthCallsIpAccessControlListMappingInstance: @@ -238,6 +376,7 @@ def get_instance( :param payload: Payload response from the API """ + return AuthCallsIpAccessControlListMappingInstance( self._version, payload, @@ -255,6 +394,7 @@ def __repr__(self) -> str: class AuthCallsIpAccessControlListMappingList(ListResource): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ Initialize the AuthCallsIpAccessControlListMappingList @@ -275,28 +415,42 @@ 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( { "IpAccessControlListSid": ip_access_control_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -304,28 +458,61 @@ 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( { "IpAccessControlListSid": ip_access_control_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -333,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, @@ -383,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, @@ -402,6 +660,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -428,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( @@ -436,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, @@ -460,9 +770,15 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 AuthCallsIpAccessControlListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -489,12 +805,90 @@ async def page_async( } ) + 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 + 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: """ @@ -507,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( @@ -523,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/__init__.py b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py index 41c1805ff2..c10c747378 100644 --- a/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py +++ b/twilio/rest/api/v2010/account/sip/domain/auth_types/auth_type_registrations/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -25,6 +24,7 @@ class AuthTypeRegistrationsList(ListResource): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ Initialize the AuthTypeRegistrationsList 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 a63a6e3290..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class AuthRegistrationsCredentialListMappingInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialListMapping 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. @@ -58,6 +57,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[AuthRegistrationsCredentialListMappingContext] = None @property @@ -95,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 @@ -113,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 @@ -126,6 +162,7 @@ def __repr__(self) -> str: class AuthRegistrationsCredentialListMappingContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): """ Initialize the AuthRegistrationsCredentialListMappingContext @@ -147,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 @@ -154,9 +205,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -166,9 +239,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AuthRegistrationsCredentialListMappingInstance 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) -> AuthRegistrationsCredentialListMappingInstance: @@ -178,19 +275,47 @@ def fetch(self) -> AuthRegistrationsCredentialListMappingInstance: :returns: The fetched AuthRegistrationsCredentialListMappingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return AuthRegistrationsCredentialListMappingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthRegistrationsCredentialListMappingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AuthRegistrationsCredentialListMappingInstance: """ @@ -199,19 +324,31 @@ async def fetch_async(self) -> AuthRegistrationsCredentialListMappingInstance: :returns: The fetched AuthRegistrationsCredentialListMappingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AuthRegistrationsCredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return AuthRegistrationsCredentialListMappingInstance( + 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: """ @@ -226,6 +363,7 @@ def __repr__(self) -> str: class AuthRegistrationsCredentialListMappingPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> AuthRegistrationsCredentialListMappingInstance: @@ -234,6 +372,7 @@ def get_instance( :param payload: Payload response from the API """ + return AuthRegistrationsCredentialListMappingInstance( self._version, payload, @@ -251,6 +390,7 @@ def __repr__(self) -> str: class AuthRegistrationsCredentialListMappingList(ListResource): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ Initialize the AuthRegistrationsCredentialListMappingList @@ -271,28 +411,40 @@ 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 - - :param credential_list_sid: The SID of the CredentialList resource to map to the SIP domain. + Internal helper for create operation - :returns: The created AuthRegistrationsCredentialListMappingInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "CredentialListSid": credential_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -300,28 +452,61 @@ 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( { "CredentialListSid": credential_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -329,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, @@ -379,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, @@ -398,6 +654,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -424,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( @@ -432,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, @@ -456,9 +764,15 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 AuthRegistrationsCredentialListMappingPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -485,12 +799,90 @@ async def page_async( } ) + 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 + 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: """ @@ -503,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( @@ -519,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 248e0ca37b..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class CredentialListMappingInstance(InstanceResource): - """ :ivar account_sid: The unique id of the Account that is responsible for this resource. :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. @@ -62,6 +61,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialListMappingContext] = None @property @@ -99,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 @@ -117,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 @@ -128,6 +164,7 @@ def __repr__(self) -> str: class CredentialListMappingContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): """ Initialize the CredentialListMappingContext @@ -149,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 @@ -156,9 +207,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -168,9 +241,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListMappingInstance 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) -> CredentialListMappingInstance: @@ -180,19 +277,47 @@ def fetch(self) -> CredentialListMappingInstance: :returns: The fetched CredentialListMappingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return CredentialListMappingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListMappingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialListMappingInstance: """ @@ -201,19 +326,31 @@ async def fetch_async(self) -> CredentialListMappingInstance: :returns: The fetched CredentialListMappingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CredentialListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return CredentialListMappingInstance( + 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: """ @@ -226,12 +363,14 @@ def __repr__(self) -> str: class CredentialListMappingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CredentialListMappingInstance: """ Build an instance of CredentialListMappingInstance :param payload: Payload response from the API """ + return CredentialListMappingInstance( self._version, payload, @@ -249,6 +388,7 @@ def __repr__(self) -> str: class CredentialListMappingList(ListResource): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ Initialize the CredentialListMappingList @@ -269,26 +409,38 @@ 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 + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "CredentialListSid": credential_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -296,28 +448,61 @@ 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( { "CredentialListSid": credential_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -325,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, @@ -375,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, @@ -394,6 +650,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -420,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( @@ -428,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, @@ -452,8 +760,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return CredentialListMappingPage(self._version, response, self._solution) + 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 CredentialListMappingPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -479,10 +795,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + return CredentialListMappingPage( + self._version, response, solution=self._solution ) - return CredentialListMappingPage(self._version, response, 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: """ @@ -494,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: """ @@ -506,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 cfe65e99dc..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class IpAccessControlListMappingInstance(InstanceResource): - """ :ivar account_sid: The unique id of the Account that is responsible for this resource. :ivar date_created: The date that this resource was created, given as GMT in [RFC 2822](https://www.php.net/manual/en/class.datetime.php#datetime.constants.rfc2822) format. @@ -62,6 +61,7 @@ def __init__( "domain_sid": domain_sid, "sid": sid or self.sid, } + self._context: Optional[IpAccessControlListMappingContext] = None @property @@ -99,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 @@ -117,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 @@ -130,6 +166,7 @@ def __repr__(self) -> str: class IpAccessControlListMappingContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, domain_sid: str, sid: str): """ Initialize the IpAccessControlListMappingContext @@ -151,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 @@ -158,9 +209,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -170,9 +243,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListMappingInstance 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) -> IpAccessControlListMappingInstance: @@ -182,19 +279,47 @@ def fetch(self) -> IpAccessControlListMappingInstance: :returns: The fetched IpAccessControlListMappingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return IpAccessControlListMappingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListMappingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> IpAccessControlListMappingInstance: """ @@ -203,19 +328,31 @@ async def fetch_async(self) -> IpAccessControlListMappingInstance: :returns: The fetched IpAccessControlListMappingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return IpAccessControlListMappingInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + domain_sid=self._solution["domain_sid"], + sid=self._solution["sid"], ) - return IpAccessControlListMappingInstance( + 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: """ @@ -228,6 +365,7 @@ def __repr__(self) -> str: class IpAccessControlListMappingPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> IpAccessControlListMappingInstance: @@ -236,6 +374,7 @@ def get_instance( :param payload: Payload response from the API """ + return IpAccessControlListMappingInstance( self._version, payload, @@ -253,6 +392,7 @@ def __repr__(self) -> str: class IpAccessControlListMappingList(ListResource): + def __init__(self, version: Version, account_sid: str, domain_sid: str): """ Initialize the IpAccessControlListMappingList @@ -273,28 +413,42 @@ 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 + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "IpAccessControlListSid": ip_access_control_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -302,28 +456,61 @@ 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( { "IpAccessControlListSid": ip_access_control_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -331,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, @@ -381,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, @@ -400,6 +658,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -426,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( @@ -434,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, @@ -458,8 +768,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return IpAccessControlListMappingPage(self._version, response, self._solution) + 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 IpAccessControlListMappingPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -485,10 +803,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return IpAccessControlListMappingPage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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: """ @@ -500,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: """ @@ -512,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 fac56d8573..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 @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class IpAccessControlListInstance(InstanceResource): - """ :ivar sid: A 34 character string that uniquely identifies this resource. :ivar account_sid: The unique id of the [Account](https://www.twilio.com/docs/iam/api/account) that owns this resource. @@ -65,6 +64,7 @@ def __init__( "account_sid": account_sid, "sid": sid or self.sid, } + self._context: Optional[IpAccessControlListContext] = None @property @@ -101,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 @@ -119,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 @@ -143,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: """ @@ -161,6 +221,7 @@ def __repr__(self) -> str: class IpAccessControlListContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the IpAccessControlListContext @@ -184,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 @@ -191,9 +266,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -203,9 +300,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance 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) -> IpAccessControlListInstance: @@ -215,18 +336,45 @@ def fetch(self) -> IpAccessControlListInstance: :returns: The fetched IpAccessControlListInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return IpAccessControlListInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return IpAccessControlListInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> IpAccessControlListInstance: """ @@ -235,12 +383,7 @@ async def fetch_async(self) -> IpAccessControlListInstance: :returns: The fetched IpAccessControlListInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return IpAccessControlListInstance( self._version, payload, @@ -248,26 +391,54 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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: 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, @@ -275,26 +446,55 @@ 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( { "FriendlyName": friendly_name, } ) + 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, + 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, @@ -302,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: """ @@ -326,12 +545,14 @@ def __repr__(self) -> str: class IpAccessControlListPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: """ Build an instance of IpAccessControlListInstance :param payload: Payload response from the API """ + return IpAccessControlListInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -346,6 +567,7 @@ def __repr__(self) -> str: class IpAccessControlListList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the IpAccessControlListList @@ -364,54 +586,108 @@ 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 + Internal helper for create operation - :param friendly_name: A human readable descriptive text that describes the IpAccessControlList, up to 255 characters long. - - :returns: The created IpAccessControlListInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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) -> 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( { "FriendlyName": friendly_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, + 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, @@ -462,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, @@ -481,6 +807,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -507,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( @@ -515,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, @@ -539,8 +917,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return IpAccessControlListPage(self._version, response, self._solution) + 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 IpAccessControlListPage(self._version, response, solution=self._solution) async def page_async( self, @@ -566,10 +950,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return IpAccessControlListPage(self._version, response, self._solution) + 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: """ @@ -581,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: """ @@ -593,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 2ce7f69f18..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class IpAddressInstance(InstanceResource): - """ :ivar sid: A 34 character string that uniquely identifies this resource. :ivar account_sid: The unique id of the Account that is responsible for this resource. @@ -70,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 @@ -107,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 @@ -125,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, @@ -167,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 @@ -178,6 +256,7 @@ def __repr__(self) -> str: class IpAddressContext(InstanceContext): + def __init__( self, version: Version, @@ -205,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 @@ -212,9 +305,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -224,9 +339,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAddressInstance 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) -> IpAddressInstance: @@ -236,19 +375,47 @@ def fetch(self) -> IpAddressInstance: :returns: The fetched IpAddressInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return 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 IpAddressInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAddressInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> IpAddressInstance: """ @@ -257,35 +424,45 @@ async def fetch_async(self) -> IpAddressInstance: :returns: The fetched IpAddressInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return 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 IpAddressInstance( + 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( + 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( { "IpAddress": ip_address, @@ -293,13 +470,36 @@ def update( "CidrPrefixLength": cidr_prefix_length, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -308,21 +508,48 @@ 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( { "IpAddress": ip_address, @@ -330,13 +557,36 @@ async def update_async( "CidrPrefixLength": cidr_prefix_length, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -345,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 @@ -356,12 +635,14 @@ def __repr__(self) -> str: class IpAddressPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> IpAddressInstance: """ Build an instance of IpAddressInstance :param payload: Payload response from the API """ + return IpAddressInstance( self._version, payload, @@ -379,6 +660,7 @@ def __repr__(self) -> str: class IpAddressList(ListResource): + def __init__( self, version: Version, account_sid: str, ip_access_control_list_sid: str ): @@ -401,21 +683,19 @@ 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( { "FriendlyName": friendly_name, @@ -423,13 +703,36 @@ def create( "CidrPrefixLength": cidr_prefix_length, } ) + 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, + 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, @@ -437,21 +740,47 @@ 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( { "FriendlyName": friendly_name, @@ -459,13 +788,36 @@ async def create_async( "CidrPrefixLength": cidr_prefix_length, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -473,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, @@ -523,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, @@ -542,6 +972,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -568,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( @@ -576,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, @@ -600,8 +1082,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return IpAddressPage(self._version, response, self._solution) + 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 IpAddressPage(self._version, response, solution=self._solution) async def page_async( self, @@ -627,10 +1115,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return IpAddressPage(self._version, response, self._solution) + 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: """ @@ -642,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: """ @@ -654,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 744bedd295..4cc10f7026 100644 --- a/twilio/rest/api/v2010/account/token.py +++ b/twilio/rest/api/v2010/account/token.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,7 +23,6 @@ class TokenInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Token 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. @@ -64,6 +63,7 @@ def __repr__(self) -> str: class TokenList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the TokenList @@ -80,56 +80,112 @@ 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( { "Ttl": ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "Ttl": ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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 2baa8af865..341c4ffdb3 100644 --- a/twilio/rest/api/v2010/account/transcription.py +++ b/twilio/rest/api/v2010/account/transcription.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class TranscriptionInstance(InstanceResource): + class Status(object): IN_PROGRESS = "in-progress" COMPLETED = "completed" @@ -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 @@ -141,6 +179,7 @@ def __repr__(self) -> str: class TranscriptionContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the TranscriptionContext @@ -160,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 @@ -167,9 +220,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -179,9 +254,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -191,18 +290,45 @@ def fetch(self) -> TranscriptionInstance: :returns: The fetched TranscriptionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return TranscriptionInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TranscriptionInstance: """ @@ -211,18 +337,29 @@ async def fetch_async(self) -> TranscriptionInstance: :returns: The fetched TranscriptionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TranscriptionInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return TranscriptionInstance( + 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: """ @@ -235,12 +372,14 @@ def __repr__(self) -> str: class TranscriptionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TranscriptionInstance: """ Build an instance of TranscriptionInstance :param payload: Payload response from the API """ + return TranscriptionInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -255,6 +394,7 @@ def __repr__(self) -> str: class TranscriptionList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the TranscriptionList @@ -323,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, @@ -342,6 +532,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -368,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( @@ -376,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, @@ -400,8 +642,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TranscriptionPage(self._version, response, self._solution) + 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 TranscriptionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -427,10 +675,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return TranscriptionPage(self._version, response, self._solution) + 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: """ @@ -442,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: """ @@ -454,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/__init__.py b/twilio/rest/api/v2010/account/usage/__init__.py index 3f3f2c76fb..8fe80f64ba 100644 --- a/twilio/rest/api/v2010/account/usage/__init__.py +++ b/twilio/rest/api/v2010/account/usage/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -24,6 +23,7 @@ class UsageList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the UsageList diff --git a/twilio/rest/api/v2010/account/usage/record/__init__.py b/twilio/rest/api/v2010/account/usage/record/__init__.py index cc22602658..a721a595d3 100644 --- a/twilio/rest/api/v2010/account/usage/record/__init__.py +++ b/twilio/rest/api/v2010/account/usage/record/__init__.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -32,330 +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" - 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" - 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" - ) - 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. @@ -375,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") @@ -409,12 +90,14 @@ def __repr__(self) -> str: class RecordPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RecordInstance: """ Build an instance of RecordInstance :param payload: Payload response from the API """ + return RecordInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -429,6 +112,7 @@ def __repr__(self) -> str: class RecordList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the RecordList @@ -458,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, @@ -471,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. @@ -497,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, @@ -510,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. @@ -534,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, @@ -548,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. @@ -561,6 +321,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -574,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, @@ -586,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. @@ -599,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( @@ -611,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, @@ -640,19 +476,25 @@ def page( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RecordPage(self._version, response, self._solution) + 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 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, @@ -679,17 +521,115 @@ async def page_async( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RecordPage(self._version, response, self._solution) + 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: """ @@ -701,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: """ @@ -713,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 0086997c79..3d01ff38a2 100644 --- a/twilio/rest/api/v2010/account/usage/record/all_time.py +++ b/twilio/rest/api/v2010/account/usage/record/all_time.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,330 +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" - 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" - 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" - ) - 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. @@ -367,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") @@ -401,12 +82,14 @@ def __repr__(self) -> str: class AllTimePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AllTimeInstance: """ Build an instance of AllTimeInstance :param payload: Payload response from the API """ + return AllTimeInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -421,6 +104,7 @@ def __repr__(self) -> str: class AllTimeList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the AllTimeList @@ -441,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, @@ -454,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. @@ -480,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, @@ -493,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. @@ -517,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, @@ -531,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. @@ -544,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -557,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, @@ -569,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. @@ -582,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( @@ -594,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, @@ -623,19 +459,25 @@ def page( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AllTimePage(self._version, response, self._solution) + 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 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, @@ -662,17 +504,115 @@ async def page_async( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return AllTimePage(self._version, response, self._solution) + 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: """ @@ -684,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: """ @@ -696,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 3fa0739ae3..0be683fb86 100644 --- a/twilio/rest/api/v2010/account/usage/record/daily.py +++ b/twilio/rest/api/v2010/account/usage/record/daily.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,330 +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" - 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" - 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" - ) - 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. @@ -367,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") @@ -401,12 +82,14 @@ def __repr__(self) -> str: class DailyPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> DailyInstance: """ Build an instance of DailyInstance :param payload: Payload response from the API """ + return DailyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -421,6 +104,7 @@ def __repr__(self) -> str: class DailyList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the DailyList @@ -441,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, @@ -454,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. @@ -480,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, @@ -493,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. @@ -517,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, @@ -531,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. @@ -544,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -557,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, @@ -569,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. @@ -582,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( @@ -594,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, @@ -623,19 +459,25 @@ def page( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DailyPage(self._version, response, self._solution) + 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 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, @@ -662,17 +504,115 @@ async def page_async( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return DailyPage(self._version, response, self._solution) + 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: """ @@ -684,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: """ @@ -696,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 028101a874..25cc8a5ce1 100644 --- a/twilio/rest/api/v2010/account/usage/record/last_month.py +++ b/twilio/rest/api/v2010/account/usage/record/last_month.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,330 +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" - 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" - 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" - ) - 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. @@ -367,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") @@ -401,12 +82,14 @@ def __repr__(self) -> str: class LastMonthPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> LastMonthInstance: """ Build an instance of LastMonthInstance :param payload: Payload response from the API """ + return LastMonthInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -421,6 +104,7 @@ def __repr__(self) -> str: class LastMonthList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the LastMonthList @@ -441,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, @@ -454,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. @@ -480,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, @@ -493,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. @@ -517,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, @@ -531,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. @@ -544,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -557,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, @@ -569,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. @@ -582,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( @@ -594,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, @@ -623,19 +459,25 @@ def page( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return LastMonthPage(self._version, response, self._solution) + 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 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, @@ -662,17 +504,115 @@ async def page_async( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return LastMonthPage(self._version, response, self._solution) + 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: """ @@ -684,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: """ @@ -696,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 62590e80ac..9d597023be 100644 --- a/twilio/rest/api/v2010/account/usage/record/monthly.py +++ b/twilio/rest/api/v2010/account/usage/record/monthly.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,330 +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" - 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" - 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" - ) - 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. @@ -367,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") @@ -401,12 +82,14 @@ def __repr__(self) -> str: class MonthlyPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MonthlyInstance: """ Build an instance of MonthlyInstance :param payload: Payload response from the API """ + return MonthlyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -421,6 +104,7 @@ def __repr__(self) -> str: class MonthlyList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the MonthlyList @@ -441,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, @@ -454,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. @@ -480,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, @@ -493,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. @@ -517,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, @@ -531,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. @@ -544,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -557,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, @@ -569,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. @@ -582,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( @@ -594,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, @@ -623,19 +459,25 @@ def page( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MonthlyPage(self._version, response, self._solution) + 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 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, @@ -662,17 +504,115 @@ async def page_async( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MonthlyPage(self._version, response, self._solution) + 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: """ @@ -684,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: """ @@ -696,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 7b5d792525..b1f11399bd 100644 --- a/twilio/rest/api/v2010/account/usage/record/this_month.py +++ b/twilio/rest/api/v2010/account/usage/record/this_month.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,330 +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" - 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" - 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" - ) - 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. @@ -367,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") @@ -401,12 +82,14 @@ def __repr__(self) -> str: class ThisMonthPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ThisMonthInstance: """ Build an instance of ThisMonthInstance :param payload: Payload response from the API """ + return ThisMonthInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -421,6 +104,7 @@ def __repr__(self) -> str: class ThisMonthList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the ThisMonthList @@ -441,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, @@ -454,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. @@ -480,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, @@ -493,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. @@ -517,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, @@ -531,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. @@ -544,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -557,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, @@ -569,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. @@ -582,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( @@ -594,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, @@ -623,19 +459,25 @@ def page( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ThisMonthPage(self._version, response, self._solution) + 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 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, @@ -662,17 +504,115 @@ async def page_async( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ThisMonthPage(self._version, response, self._solution) + 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: """ @@ -684,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: """ @@ -696,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 c499b7f1aa..dfe2e1fca4 100644 --- a/twilio/rest/api/v2010/account/usage/record/today.py +++ b/twilio/rest/api/v2010/account/usage/record/today.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,330 +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" - 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" - 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" - ) - 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. @@ -367,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") @@ -401,12 +82,14 @@ def __repr__(self) -> str: class TodayPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TodayInstance: """ Build an instance of TodayInstance :param payload: Payload response from the API """ + return TodayInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -421,6 +104,7 @@ def __repr__(self) -> str: class TodayList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the TodayList @@ -441,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, @@ -454,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. @@ -480,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, @@ -493,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. @@ -517,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, @@ -531,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. @@ -544,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -557,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, @@ -569,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. @@ -582,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( @@ -594,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, @@ -623,19 +459,25 @@ def page( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TodayPage(self._version, response, self._solution) + 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 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, @@ -662,17 +504,115 @@ async def page_async( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return TodayPage(self._version, response, self._solution) + 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: """ @@ -684,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: """ @@ -696,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 88c1082b7b..24812d72a3 100644 --- a/twilio/rest/api/v2010/account/usage/record/yearly.py +++ b/twilio/rest/api/v2010/account/usage/record/yearly.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,330 +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" - 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" - 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" - ) - 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. @@ -367,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") @@ -401,12 +82,14 @@ def __repr__(self) -> str: class YearlyPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> YearlyInstance: """ Build an instance of YearlyInstance :param payload: Payload response from the API """ + return YearlyInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -421,6 +104,7 @@ def __repr__(self) -> str: class YearlyList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the YearlyList @@ -441,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, @@ -454,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. @@ -480,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, @@ -493,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. @@ -517,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, @@ -531,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. @@ -544,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -557,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, @@ -569,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. @@ -582,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( @@ -594,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, @@ -623,19 +459,25 @@ def page( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return YearlyPage(self._version, response, self._solution) + 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 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, @@ -662,17 +504,115 @@ async def page_async( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return YearlyPage(self._version, response, self._solution) + 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: """ @@ -684,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: """ @@ -696,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 b5307b6417..32ad22f8d0 100644 --- a/twilio/rest/api/v2010/account/usage/record/yesterday.py +++ b/twilio/rest/api/v2010/account/usage/record/yesterday.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,330 +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" - 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" - 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" - ) - 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. @@ -367,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") @@ -401,12 +82,14 @@ def __repr__(self) -> str: class YesterdayPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> YesterdayInstance: """ Build an instance of YesterdayInstance :param payload: Payload response from the API """ + return YesterdayInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -421,6 +104,7 @@ def __repr__(self) -> str: class YesterdayList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the YesterdayList @@ -441,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, @@ -454,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. @@ -480,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, @@ -493,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. @@ -517,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, @@ -531,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. @@ -544,6 +304,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( category=category, @@ -557,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, @@ -569,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. @@ -582,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( @@ -594,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, @@ -623,19 +459,25 @@ def page( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "IncludeSubaccounts": serialize.boolean_to_string(include_subaccounts), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return YesterdayPage(self._version, response, self._solution) + 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 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, @@ -662,17 +504,115 @@ async def page_async( "Category": category, "StartDate": serialize.iso8601_date(start_date), "EndDate": serialize.iso8601_date(end_date), - "IncludeSubaccounts": include_subaccounts, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return YesterdayPage(self._version, response, self._solution) + 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: """ @@ -684,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: """ @@ -696,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 9a5654b3c8..8e975e0204 100644 --- a/twilio/rest/api/v2010/account/usage/trigger.py +++ b/twilio/rest/api/v2010/account/usage/trigger.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class TriggerInstance(InstanceResource): + class Recurring(object): DAILY = "daily" MONTHLY = "monthly" @@ -35,325 +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" - 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" - 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" - ) - 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. @@ -369,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`. """ @@ -404,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 @@ -449,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 @@ -467,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, @@ -509,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 @@ -520,6 +279,7 @@ def __repr__(self) -> str: class TriggerContext(InstanceContext): + def __init__(self, version: Version, account_sid: str, sid: str): """ Initialize the TriggerContext @@ -539,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 @@ -546,9 +320,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -558,9 +354,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TriggerInstance 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) -> TriggerInstance: @@ -570,18 +390,45 @@ def fetch(self) -> TriggerInstance: :returns: The fetched TriggerInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return TriggerInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TriggerInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TriggerInstance: """ @@ -590,34 +437,43 @@ async def fetch_async(self) -> TriggerInstance: :returns: The fetched TriggerInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TriggerInstance( + self._version, + payload, + account_sid=self._solution["account_sid"], + sid=self._solution["sid"], ) - return TriggerInstance( + 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( + 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 - - :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. + Internal helper for update operation - :returns: The updated TriggerInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "CallbackMethod": callback_method, @@ -625,13 +481,36 @@ def update( "FriendlyName": friendly_name, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -639,21 +518,47 @@ 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( { "CallbackMethod": callback_method, @@ -661,13 +566,36 @@ async def update_async( "FriendlyName": friendly_name, } ) + 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, + 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, @@ -675,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 @@ -686,12 +642,14 @@ def __repr__(self) -> str: class TriggerPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TriggerInstance: """ Build an instance of TriggerInstance :param payload: Payload response from the API """ + return TriggerInstance( self._version, payload, account_sid=self._solution["account_sid"] ) @@ -706,6 +664,7 @@ def __repr__(self) -> str: class TriggerList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the TriggerList @@ -724,29 +683,23 @@ 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( { "CallbackUrl": callback_url, @@ -758,40 +711,106 @@ def create( "TriggerBy": trigger_by, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "CallbackUrl": callback_url, @@ -803,22 +822,94 @@ async def create_async( "TriggerBy": trigger_by, } ) + 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, + 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]: @@ -830,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 @@ -854,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]: @@ -866,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 @@ -886,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]: @@ -901,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 @@ -911,6 +1072,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( recurring=recurring, @@ -925,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]: @@ -936,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 @@ -946,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( @@ -957,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, @@ -990,14 +1221,20 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TriggerPage(self._version, response, self._solution) + 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 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, @@ -1026,10 +1263,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return TriggerPage(self._version, response, self._solution) + 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: """ @@ -1041,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: """ @@ -1053,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 84ef8ee253..9594e19cc1 100644 --- a/twilio/rest/api/v2010/account/validation_request.py +++ b/twilio/rest/api/v2010/account/validation_request.py @@ -12,9 +12,9 @@ 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 @@ -22,7 +22,6 @@ class ValidationRequestInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for the Caller ID. :ivar call_sid: The SID of the [Call](https://www.twilio.com/docs/voice/api/call-resource) the Caller ID is associated with. @@ -55,6 +54,7 @@ def __repr__(self) -> str: class ValidationRequestList(ListResource): + def __init__(self, version: Version, account_sid: str): """ Initialize the ValidationRequestList @@ -73,6 +73,42 @@ def __init__(self, version: Version, account_sid: str): **self._solution ) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PhoneNumber": phone_number, + "FriendlyName": friendly_name, + "CallDelay": call_delay, + "Extension": extension, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + } + ) + 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, @@ -94,6 +130,68 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "PhoneNumber": phone_number, @@ -104,15 +202,14 @@ def create( "StatusCallbackMethod": status_callback_method, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ValidationRequestInstance( - self._version, payload, account_sid=self._solution["account_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( @@ -136,26 +233,51 @@ async def create_async( :returns: The created ValidationRequestInstance """ - data = values.of( - { - "PhoneNumber": phone_number, - "FriendlyName": friendly_name, - "CallDelay": call_delay, - "Extension": extension, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return ValidationRequestInstance( + self._version, payload, account_sid=self._solution["account_sid"] ) - return ValidationRequestInstance( + 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: """ diff --git a/twilio/rest/microvisor/MicrovisorBase.py b/twilio/rest/assistants/AssistantsBase.py similarity index 75% rename from twilio/rest/microvisor/MicrovisorBase.py rename to twilio/rest/assistants/AssistantsBase.py index 57a4c50f55..a9c9e9afcd 100644 --- a/twilio/rest/microvisor/MicrovisorBase.py +++ b/twilio/rest/assistants/AssistantsBase.py @@ -13,23 +13,24 @@ from twilio.base.domain import Domain from twilio.rest import Client -from twilio.rest.microvisor.v1 import V1 +from twilio.rest.assistants.v1 import V1 -class MicrovisorBase(Domain): +class AssistantsBase(Domain): + def __init__(self, twilio: Client): """ - Initialize the Microvisor Domain + Initialize the Assistants Domain - :returns: Domain for Microvisor + :returns: Domain for Assistants """ - super().__init__(twilio, "https://microvisor.twilio.com") + super().__init__(twilio, "https://assistants.twilio.com") self._v1: Optional[V1] = None @property def v1(self) -> V1: """ - :returns: Versions v1 of Microvisor + :returns: Versions v1 of Assistants """ if self._v1 is None: self._v1 = V1(self) @@ -40,4 +41,4 @@ def __repr__(self) -> str: Provide a friendly representation :returns: Machine friendly representation """ - return "" + return "" diff --git a/twilio/rest/assistants/__init__.py b/twilio/rest/assistants/__init__.py new file mode 100644 index 0000000000..889daf9d29 --- /dev/null +++ b/twilio/rest/assistants/__init__.py @@ -0,0 +1,56 @@ +from warnings import warn + +from twilio.rest.assistants.AssistantsBase 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 new file mode 100644 index 0000000000..546ad14554 --- /dev/null +++ b/twilio/rest/assistants/v1/__init__.py @@ -0,0 +1,75 @@ +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 new file mode 100644 index 0000000000..aa3c171f63 --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/__init__.py @@ -0,0 +1,1499 @@ +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.api_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.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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantInstance 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 AssistantInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssistantInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssistantInstance 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_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, + ) + + def update_with_http_info( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the AssistantInstance with HTTP info + + :param assistants_v1_service_update_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request, + ) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AssistantInstance with HTTP info + + :param assistants_v1_service_update_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> 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 AssistantInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantInstance 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 AssistantInstance + + + :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 AssistantInstance 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) -> AssistantInstance: + """ + Fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + payload, _, _ = self._fetch() + return AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssistantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = AssistantInstance( + 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) -> AssistantInstance: + """ + Asynchronous coroutine to fetch the AssistantInstance + + + :returns: The fetched AssistantInstance + """ + payload, _, _ = await self._fetch_async() + return AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the AssistantInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = AssistantInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_assistant_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, + 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 + """ + payload, _, _ = self._update( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request + ) + return AssistantInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the AssistantInstance and return response metadata + + :param assistants_v1_service_update_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request + ) + instance = AssistantInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_assistant_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, + 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 + """ + payload, _, _ = await self._update_async( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request + ) + return AssistantInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_assistant_request: Union[ + AssistantsV1ServiceUpdateAssistantRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the AssistantInstance and return response metadata + + :param assistants_v1_service_update_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + assistants_v1_service_update_assistant_request=assistants_v1_service_update_assistant_request + ) + instance = AssistantInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + assistants_v1_service_create_assistant_request=assistants_v1_service_create_assistant_request + ) + return AssistantInstance(self._version, payload) + + def create_with_http_info( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> ApiResponse: + """ + Create the AssistantInstance and return response metadata + + :param assistants_v1_service_create_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_create_assistant_request=assistants_v1_service_create_assistant_request + ) + instance = AssistantInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + assistants_v1_service_create_assistant_request=assistants_v1_service_create_assistant_request + ) + return AssistantInstance(self._version, payload) + + async def create_with_http_info_async( + self, + assistants_v1_service_create_assistant_request: AssistantsV1ServiceCreateAssistantRequest, + ) -> ApiResponse: + """ + Asynchronously create the AssistantInstance and return response metadata + + :param assistants_v1_service_create_assistant_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_create_assistant_request=assistants_v1_service_create_assistant_request + ) + instance = AssistantInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssistantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple 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 AssistantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, 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[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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssistantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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 AssistantInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. 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, + ) -> 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 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 AssistantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssistantPage(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 AssistantPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssistantPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 new file mode 100644 index 0000000000..e5d6ed5daa --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/assistants_knowledge.py @@ -0,0 +1,871 @@ +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.api_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 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 create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsKnowledgeInstance 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 AssistantsKnowledgeInstance 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 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantsKnowledgeInstance 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 AssistantsKnowledgeInstance 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 + + :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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self) -> AssistantsKnowledgeInstance: + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + payload, _, _ = self._create() + return AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + 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) + """ + + data = values.of({}) + headers = values.of({}) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self) -> AssistantsKnowledgeInstance: + """ + Asynchronous coroutine to create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + payload, _, _ = await self._create_async() + return AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = AssistantsKnowledgeInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + 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: + """ + Deletes the AssistantsKnowledgeInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantsKnowledgeInstance 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 AssistantsKnowledgeInstance + + + :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 AssistantsKnowledgeInstance 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 __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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> AssistantsKnowledgeInstance: + """ + Create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + payload, _, _ = self._create() + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_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"}) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) + + async def create_async(self) -> AssistantsKnowledgeInstance: + """ + Asynchronously create the AssistantsKnowledgeInstance + + + :returns: The created AssistantsKnowledgeInstance + """ + payload, _, _ = await self._create_async() + return AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the AssistantsKnowledgeInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = AssistantsKnowledgeInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssistantsKnowledgeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple 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 AssistantsKnowledgeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, 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[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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssistantsKnowledgeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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 AssistantsKnowledgeInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. 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, + ) -> 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, 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, + ) -> 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, 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 AssistantsKnowledgePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssistantsKnowledgePage(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 AssistantsKnowledgePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssistantsKnowledgePage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 new file mode 100644 index 0000000000..eb7ab6b8c1 --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/assistants_tool.py @@ -0,0 +1,869 @@ +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.api_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 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 create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsToolInstance 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 AssistantsToolInstance 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 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantsToolInstance 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 AssistantsToolInstance 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 + + :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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create(self) -> AssistantsToolInstance: + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + payload, _, _ = self._create() + return AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + 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) + """ + + data = values.of({}) + headers = values.of({}) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def create_async(self) -> AssistantsToolInstance: + """ + Asynchronous coroutine to create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + payload, _, _ = await self._create_async() + return AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to create the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = AssistantsToolInstance( + self._version, + payload, + assistant_id=self._solution["assistant_id"], + id=self._solution["id"], + ) + 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: + """ + Deletes the AssistantsToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the AssistantsToolInstance 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 AssistantsToolInstance + + + :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 AssistantsToolInstance 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 __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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + return self._version.create_with_response_info( + method="POST", uri=self._uri, headers=headers + ) + + def create(self) -> AssistantsToolInstance: + """ + Create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + payload, _, _ = self._create() + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create() + instance = AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_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"}) + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) + + async def create_async(self) -> AssistantsToolInstance: + """ + Asynchronously create the AssistantsToolInstance + + + :returns: The created AssistantsToolInstance + """ + payload, _, _ = await self._create_async() + return AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the AssistantsToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async() + instance = AssistantsToolInstance( + self._version, payload, assistant_id=self._solution["assistant_id"] + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams AssistantsToolInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple 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 AssistantsToolInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, 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[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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists AssistantsToolInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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 AssistantsToolInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. 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, + ) -> 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, 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, + ) -> 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, 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 AssistantsToolPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = AssistantsToolPage(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 AssistantsToolPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = AssistantsToolPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 new file mode 100644 index 0000000000..b52770b788 --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/feedback.py @@ -0,0 +1,638 @@ +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.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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + assistants_v1_service_create_feedback_request=assistants_v1_service_create_feedback_request + ) + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + def create_with_http_info( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> ApiResponse: + """ + Create the FeedbackInstance and return response metadata + + :param assistants_v1_service_create_feedback_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_create_feedback_request=assistants_v1_service_create_feedback_request + ) + instance = FeedbackInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + assistants_v1_service_create_feedback_request=assistants_v1_service_create_feedback_request + ) + return FeedbackInstance(self._version, payload, id=self._solution["id"]) + + async def create_with_http_info_async( + self, + assistants_v1_service_create_feedback_request: AssistantsV1ServiceCreateFeedbackRequest, + ) -> ApiResponse: + """ + Asynchronously create the FeedbackInstance and return response metadata + + :param assistants_v1_service_create_feedback_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_create_feedback_request=assistants_v1_service_create_feedback_request + ) + instance = FeedbackInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams FeedbackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple 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 FeedbackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, 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[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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists FeedbackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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 FeedbackInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. 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, + ) -> 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, 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, + ) -> 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, 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 FeedbackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = FeedbackPage(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 FeedbackPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + response, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = FeedbackPage(self._version, response, solution=self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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, solution=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, solution=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 new file mode 100644 index 0000000000..38adca4cec --- /dev/null +++ b/twilio/rest/assistants/v1/assistant/message.py @@ -0,0 +1,247 @@ +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.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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + assistants_v1_service_assistant_send_message_request=assistants_v1_service_assistant_send_message_request + ) + return MessageInstance(self._version, payload, id=self._solution["id"]) + + def create_with_http_info( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> ApiResponse: + """ + Create the MessageInstance and return response metadata + + :param assistants_v1_service_assistant_send_message_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_assistant_send_message_request=assistants_v1_service_assistant_send_message_request + ) + instance = MessageInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + assistants_v1_service_assistant_send_message_request=assistants_v1_service_assistant_send_message_request + ) + return MessageInstance(self._version, payload, id=self._solution["id"]) + + async def create_with_http_info_async( + self, + assistants_v1_service_assistant_send_message_request: AssistantsV1ServiceAssistantSendMessageRequest, + ) -> ApiResponse: + """ + Asynchronously create the MessageInstance and return response metadata + + :param assistants_v1_service_assistant_send_message_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_assistant_send_message_request=assistants_v1_service_assistant_send_message_request + ) + instance = MessageInstance(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 "" diff --git a/twilio/rest/assistants/v1/knowledge/__init__.py b/twilio/rest/assistants/v1/knowledge/__init__.py new file mode 100644 index 0000000000..e31a496d94 --- /dev/null +++ b/twilio/rest/assistants/v1/knowledge/__init__.py @@ -0,0 +1,1443 @@ +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.api_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 + + +class KnowledgeInstance(InstanceResource): + + class AssistantsV1ServiceCreateKnowledgeRequest(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. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + 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 + ] = 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, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + 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 AssistantsV1ServiceUpdateKnowledgeRequest(object): + """ + :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 knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + 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 + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + """ + :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], 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 = { + "id": id or self.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, + id=self._solution["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, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> "KnowledgeInstance": + """ + Update the KnowledgeInstance + + :param assistants_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, + ) + + async def update_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> "KnowledgeInstance": + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param assistants_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, + ) + + def update_with_http_info( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance with HTTP info + + :param assistants_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request, + ) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance with HTTP info + + :param assistants_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request, + ) + + @property + def chunks(self) -> ChunkList: + """ + Access the chunks + """ + return self._proxy.chunks + + @property + def knowledge_status(self) -> KnowledgeStatusList: + """ + Access the knowledge_status + """ + return self._proxy.knowledge_status + + 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 KnowledgeContext(InstanceContext): + + class AssistantsV1ServiceCreateKnowledgeRequest(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. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + 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 + ] = 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, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + 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 AssistantsV1ServiceUpdateKnowledgeRequest(object): + """ + :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 knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + 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 + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}".format(**self._solution) + + 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 + + + :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 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, + id=self._solution["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, + 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) -> 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"], + ) + + 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 + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_knowledge_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, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + payload, _, _ = self._update( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request + ) + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the KnowledgeInstance and return response metadata + + :param assistants_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + assistants_v1_service_update_knowledge_request=assistants_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, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_knowledge_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, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Asynchronous coroutine to update the KnowledgeInstance + + :param assistants_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + payload, _, _ = await self._update_async( + assistants_v1_service_update_knowledge_request=assistants_v1_service_update_knowledge_request + ) + return KnowledgeInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_knowledge_request: Union[ + AssistantsV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the KnowledgeInstance and return response metadata + + :param assistants_v1_service_update_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + assistants_v1_service_update_knowledge_request=assistants_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: + """ + Access the chunks + """ + if self._chunks is None: + self._chunks = ChunkList( + self._version, + self._solution["id"], + ) + return self._chunks + + @property + def knowledge_status(self) -> KnowledgeStatusList: + """ + Access the knowledge_status + """ + if self._knowledge_status is None: + self._knowledge_status = KnowledgeStatusList( + self._version, + self._solution["id"], + ) + return self._knowledge_status + + 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 KnowledgePage(Page): + + 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) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class KnowledgeList(ListResource): + + class AssistantsV1ServiceCreateKnowledgeRequest(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. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + 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 + ] = 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, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + 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 AssistantsV1ServiceUpdateKnowledgeRequest(object): + """ + :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 knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + 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 + ] = payload.get("policy") + self.type: Optional[str] = payload.get("type") + self.embedding_model: Optional[str] = payload.get("embedding_model") + + def to_dict(self): + return { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + def __init__(self, version: Version): + """ + Initialize the KnowledgeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Knowledge" + + def _create( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_create_knowledge_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, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Create the KnowledgeInstance + + :param assistants_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + payload, _, _ = self._create( + assistants_v1_service_create_knowledge_request=assistants_v1_service_create_knowledge_request + ) + return KnowledgeInstance(self._version, payload) + + def create_with_http_info( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> ApiResponse: + """ + Create the KnowledgeInstance and return response metadata + + :param assistants_v1_service_create_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_create_knowledge_request=assistants_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, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_create_knowledge_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, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Asynchronously create the KnowledgeInstance + + :param assistants_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + payload, _, _ = await self._create_async( + assistants_v1_service_create_knowledge_request=assistants_v1_service_create_knowledge_request + ) + return KnowledgeInstance(self._version, payload) + + async def create_with_http_info_async( + self, + assistants_v1_service_create_knowledge_request: AssistantsV1ServiceCreateKnowledgeRequest, + ) -> ApiResponse: + """ + Asynchronously create the KnowledgeInstance and return response metadata + + :param assistants_v1_service_create_knowledge_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_create_knowledge_request=assistants_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, + 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 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[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 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 stream_with_http_info( + self, + assistant_id: 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 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + assistant_id=assistant_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, + assistant_id: 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 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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + assistant_id=assistant_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, + assistant_id: 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 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[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 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 list_with_http_info( + self, + assistant_id: 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 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + assistant_id=assistant_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, + assistant_id: 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 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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + assistant_id=assistant_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, + 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, + ) -> KnowledgePage: + """ + Retrieve a single page of KnowledgeInstance 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 KnowledgeInstance + """ + 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 KnowledgePage(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, + ) -> KnowledgePage: + """ + Asynchronously retrieve a single page of KnowledgeInstance 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 KnowledgeInstance + """ + 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 KnowledgePage(self._version, response) + + def page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with KnowledgePage, status code, and headers + """ + 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, 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, + 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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with KnowledgePage, status code, and headers + """ + 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, 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. + 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) + + 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) + + def get(self, id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param id: + """ + return KnowledgeContext(self._version, id=id) + + def __call__(self, id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param id: + """ + return KnowledgeContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/assistants/v1/knowledge/chunk.py b/twilio/rest/assistants/v1/knowledge/chunk.py new file mode 100644 index 0000000000..fba901e7d1 --- /dev/null +++ b/twilio/rest/assistants/v1/knowledge/chunk.py @@ -0,0 +1,471 @@ +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.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 ChunkInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar content: The chunk content. + :ivar metadata: The metadata of the chunk. + :ivar date_created: The date and time in GMT when the Chunk 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 Chunk was 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.account_sid: Optional[str] = payload.get("account_sid") + self.content: Optional[str] = payload.get("content") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + 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 ChunkPage(Page): + + 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, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChunkList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the ChunkList + + :param version: Version that contains the resource + :param id: The knowledge ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}/Chunks".format(**self._solution) + + def stream( + self, + 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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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[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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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 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, + 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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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[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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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 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, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChunkPage: + """ + Retrieve a single page of ChunkInstance 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 ChunkInstance + """ + data = values.of( + { + "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 ChunkPage(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, + ) -> ChunkPage: + """ + Asynchronously retrieve a single page of ChunkInstance 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 ChunkInstance + """ + data = values.of( + { + "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 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: + """ + 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 "" diff --git a/twilio/rest/assistants/v1/knowledge/knowledge_status.py b/twilio/rest/assistants/v1/knowledge/knowledge_status.py new file mode 100644 index 0000000000..a6881230e3 --- /dev/null +++ b/twilio/rest/assistants/v1/knowledge/knowledge_status.py @@ -0,0 +1,264 @@ +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, 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 KnowledgeStatusInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar status: The status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar last_status: The last status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :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], id: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional[str] = payload.get("status") + self.last_status: Optional[str] = payload.get("last_status") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id, + } + + self._context: Optional[KnowledgeStatusContext] = None + + @property + def _proxy(self) -> "KnowledgeStatusContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KnowledgeStatusContext for this KnowledgeStatusInstance + """ + if self._context is None: + self._context = KnowledgeStatusContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "KnowledgeStatusInstance": + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KnowledgeStatusInstance": + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KnowledgeStatusContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeStatusContext + + :param version: Version that contains the resource + :param id: the Knowledge ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}/Status".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) -> KnowledgeStatusInstance: + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + payload, _, _ = self._fetch() + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeStatusInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KnowledgeStatusList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeStatusList + + :param version: Version that contains the resource + :param id: the Knowledge ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + + def get(self) -> KnowledgeStatusContext: + """ + Constructs a KnowledgeStatusContext + + """ + return KnowledgeStatusContext(self._version, id=self._solution["id"]) + + def __call__(self) -> KnowledgeStatusContext: + """ + Constructs a KnowledgeStatusContext + + """ + return KnowledgeStatusContext(self._version, 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 new file mode 100644 index 0000000000..37d5bb1def --- /dev/null +++ b/twilio/rest/assistants/v1/policy.py @@ -0,0 +1,540 @@ +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.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 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 stream_with_http_info( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams PolicyInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + tool_id=tool_id, knowledge_id=knowledge_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, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams PolicyInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + tool_id=tool_id, knowledge_id=knowledge_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, + 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 list_with_http_info( + self, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists PolicyInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + tool_id=tool_id, + knowledge_id=knowledge_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, + tool_id: Union[str, object] = values.unset, + knowledge_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists PolicyInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + tool_id=tool_id, + knowledge_id=knowledge_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, + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with PolicyPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = PolicyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with PolicyPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = PolicyPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 new file mode 100644 index 0000000000..26b17a103c --- /dev/null +++ b/twilio/rest/assistants/v1/session/__init__.py @@ -0,0 +1,680 @@ +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.api_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.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() + + 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() + + @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) -> 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) -> SessionInstance: + """ + Fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + payload, _, _ = self._fetch() + return SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SessionInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = SessionInstance( + 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) -> SessionInstance: + """ + Asynchronous coroutine to fetch the SessionInstance + + + :returns: The fetched SessionInstance + """ + payload, _, _ = await self._fetch_async() + return SessionInstance( + self._version, + payload, + id=self._solution["id"], + ) + + 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, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @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 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, + 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 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, + 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 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) + 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) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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 new file mode 100644 index 0000000000..f8fba1fbde --- /dev/null +++ b/twilio/rest/assistants/v1/session/message.py @@ -0,0 +1,483 @@ +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.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 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 stream_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams MessageInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple 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 MessageInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, stream() will attempt to read the + limit with the most efficient page size, i.e. min(limit, 1000) + + :returns: tuple of (generator, 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[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 list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists MessageInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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 MessageInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. 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, + ) -> 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, 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, + ) -> 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, 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 MessagePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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, + page_token: Union[str, object] = values.unset, + 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 MessagePage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: + """ + 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, solution=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, solution=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 new file mode 100644 index 0000000000..13f2c71aaa --- /dev/null +++ b/twilio/rest/assistants/v1/tool.py @@ -0,0 +1,1397 @@ +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.api_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 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 delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ToolInstance 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 ToolInstance with HTTP info + + + :returns: ApiResponse with success boolean, status code, and headers + """ + return await self._proxy.delete_with_http_info_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 fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ToolInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ToolInstance 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_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 update_with_http_info( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ToolInstance with HTTP info + + :param assistants_v1_service_update_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request, + ) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ToolInstance with HTTP info + + :param assistants_v1_service_update_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_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) -> 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 ToolInstance + + + :returns: True if delete succeeds, False otherwise + """ + success, _, _ = self._delete() + return success + + def delete_with_http_info(self) -> ApiResponse: + """ + Deletes the ToolInstance 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 ToolInstance + + + :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 ToolInstance 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) -> ToolInstance: + """ + Fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + payload, _, _ = self._fetch() + return ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch() + instance = ToolInstance( + 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) -> ToolInstance: + """ + Asynchronous coroutine to fetch the ToolInstance + + + :returns: The fetched ToolInstance + """ + payload, _, _ = await self._fetch_async() + return ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ToolInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async() + instance = ToolInstance( + self._version, + payload, + id=self._solution["id"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_tool_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, + 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 + """ + payload, _, _ = self._update( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request + ) + return ToolInstance(self._version, payload, id=self._solution["id"]) + + def update_with_http_info( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Update the ToolInstance and return response metadata + + :param assistants_v1_service_update_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._update( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request + ) + instance = ToolInstance(self._version, payload, id=self._solution["id"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _update_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal async helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = assistants_v1_service_update_tool_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, + 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 + """ + payload, _, _ = await self._update_async( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request + ) + return ToolInstance(self._version, payload, id=self._solution["id"]) + + async def update_with_http_info_async( + self, + assistants_v1_service_update_tool_request: Union[ + AssistantsV1ServiceUpdateToolRequest, object + ] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the ToolInstance and return response metadata + + :param assistants_v1_service_update_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._update_async( + assistants_v1_service_update_tool_request=assistants_v1_service_update_tool_request + ) + instance = ToolInstance(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 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = self._create( + assistants_v1_service_create_tool_request=assistants_v1_service_create_tool_request + ) + return ToolInstance(self._version, payload) + + def create_with_http_info( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> ApiResponse: + """ + Create the ToolInstance and return response metadata + + :param assistants_v1_service_create_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + assistants_v1_service_create_tool_request=assistants_v1_service_create_tool_request + ) + instance = ToolInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async def _create_async( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + 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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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 + """ + payload, _, _ = await self._create_async( + assistants_v1_service_create_tool_request=assistants_v1_service_create_tool_request + ) + return ToolInstance(self._version, payload) + + async def create_with_http_info_async( + self, + assistants_v1_service_create_tool_request: AssistantsV1ServiceCreateToolRequest, + ) -> ApiResponse: + """ + Asynchronously create the ToolInstance and return response metadata + + :param assistants_v1_service_create_tool_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + assistants_v1_service_create_tool_request=assistants_v1_service_create_tool_request + ) + instance = ToolInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + 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 stream_with_http_info( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Streams ToolInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_with_http_info( + assistant_id=assistant_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, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> tuple: + """ + Asynchronously streams ToolInstance and returns headers from first page + + + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_with_http_info_async( + assistant_id=assistant_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, + 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 list_with_http_info( + self, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ToolInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = self.stream_with_http_info( + assistant_id=assistant_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, + assistant_id: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Asynchronously lists ToolInstance and returns headers from first page + + + :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: ApiResponse with list of instances, status code, and headers + """ + generator, status_code, headers = await self.stream_with_http_info_async( + assistant_id=assistant_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, + 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 page_with_http_info( + 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, + ) -> ApiResponse: + """ + Retrieve a single page with response metadata + + + :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: ApiResponse with ToolPage, status code, and headers + """ + 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, status_code, response_headers = self._version.page_with_response_info( + method="GET", uri=self._uri, params=data, headers=headers + ) + page = ToolPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + async def page_with_http_info_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, + ) -> ApiResponse: + """ + Asynchronously retrieve a single page with response metadata + + + :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: ApiResponse with ToolPage, status code, and headers + """ + 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, status_code, response_headers = ( + await self._version.page_with_response_info_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + ) + page = ToolPage(self._version, response) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) + + 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/autopilot/__init__.py b/twilio/rest/autopilot/__init__.py deleted file mode 100644 index f382325023..0000000000 --- a/twilio/rest/autopilot/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -from warnings import warn - -from twilio.rest.autopilot.AutopilotBase import AutopilotBase -from twilio.rest.autopilot.v1.assistant import AssistantList -from twilio.rest.autopilot.v1.restore_assistant import RestoreAssistantList - - -class Autopilot(AutopilotBase): - @property - def assistants(self) -> AssistantList: - warn( - "assistants is deprecated. Use v1.assistants instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.assistants - - @property - def restore_assistant(self) -> RestoreAssistantList: - warn( - "restore_assistant is deprecated. Use v1.restore_assistant instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.restore_assistant diff --git a/twilio/rest/autopilot/v1/assistant/__init__.py b/twilio/rest/autopilot/v1/assistant/__init__.py deleted file mode 100644 index a25268fc45..0000000000 --- a/twilio/rest/autopilot/v1/assistant/__init__.py +++ /dev/null @@ -1,879 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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.autopilot.v1.assistant.defaults import DefaultsList -from twilio.rest.autopilot.v1.assistant.dialogue import DialogueList -from twilio.rest.autopilot.v1.assistant.field_type import FieldTypeList -from twilio.rest.autopilot.v1.assistant.model_build import ModelBuildList -from twilio.rest.autopilot.v1.assistant.query import QueryList -from twilio.rest.autopilot.v1.assistant.style_sheet import StyleSheetList -from twilio.rest.autopilot.v1.assistant.task import TaskList -from twilio.rest.autopilot.v1.assistant.webhook import WebhookList - - -class AssistantInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Assistant resource. - :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. It is not unique and can be up to 255 characters long. - :ivar latest_model_build_sid: Reserved. - :ivar links: A list of the URLs of the Assistant's related resources. - :ivar log_queries: Whether queries should be logged and kept after training. Can be: `true` or `false` and defaults to `true`. If `true`, queries are stored for 30 days, and then deleted. If `false`, no queries are stored. - :ivar development_stage: A string describing the state of the assistant. - :ivar needs_model_build: Whether model needs to be rebuilt. - :ivar sid: The unique string that we created to identify the Assistant 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. It can be up to 64 characters long. - :ivar url: The absolute URL of the Assistant resource. - :ivar callback_url: Reserved. - :ivar callback_events: Reserved. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.friendly_name: Optional[str] = payload.get("friendly_name") - self.latest_model_build_sid: Optional[str] = payload.get( - "latest_model_build_sid" - ) - self.links: Optional[Dict[str, object]] = payload.get("links") - self.log_queries: Optional[bool] = payload.get("log_queries") - self.development_stage: Optional[str] = payload.get("development_stage") - self.needs_model_build: Optional[bool] = payload.get("needs_model_build") - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.url: Optional[str] = payload.get("url") - self.callback_url: Optional[str] = payload.get("callback_url") - self.callback_events: Optional[str] = payload.get("callback_events") - - self._solution = { - "sid": sid or self.sid, - } - 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, - sid=self._solution["sid"], - ) - 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, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - defaults: Union[object, object] = values.unset, - development_stage: Union[str, object] = values.unset, - ) -> "AssistantInstance": - """ - Update the AssistantInstance - - :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 log_queries: Whether queries should be logged and kept after training. Can be: `true` or `false` and defaults to `true`. If `true`, queries are stored for 30 days, and then deleted. If `false`, no queries are stored. - :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. The first 64 characters must be unique. - :param callback_url: Reserved. - :param callback_events: Reserved. - :param style_sheet: The JSON string that defines the Assistant's [style sheet](https://www.twilio.com/docs/autopilot/api/assistant/stylesheet) - :param defaults: A JSON object that defines the Assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios, including initiation actions and fallback tasks. - :param development_stage: A string describing the state of the assistant. - - :returns: The updated AssistantInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - log_queries=log_queries, - unique_name=unique_name, - callback_url=callback_url, - callback_events=callback_events, - style_sheet=style_sheet, - defaults=defaults, - development_stage=development_stage, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - defaults: Union[object, object] = values.unset, - development_stage: Union[str, object] = values.unset, - ) -> "AssistantInstance": - """ - Asynchronous coroutine to update the AssistantInstance - - :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 log_queries: Whether queries should be logged and kept after training. Can be: `true` or `false` and defaults to `true`. If `true`, queries are stored for 30 days, and then deleted. If `false`, no queries are stored. - :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. The first 64 characters must be unique. - :param callback_url: Reserved. - :param callback_events: Reserved. - :param style_sheet: The JSON string that defines the Assistant's [style sheet](https://www.twilio.com/docs/autopilot/api/assistant/stylesheet) - :param defaults: A JSON object that defines the Assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios, including initiation actions and fallback tasks. - :param development_stage: A string describing the state of the assistant. - - :returns: The updated AssistantInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - log_queries=log_queries, - unique_name=unique_name, - callback_url=callback_url, - callback_events=callback_events, - style_sheet=style_sheet, - defaults=defaults, - development_stage=development_stage, - ) - - @property - def defaults(self) -> DefaultsList: - """ - Access the defaults - """ - return self._proxy.defaults - - @property - def dialogues(self) -> DialogueList: - """ - Access the dialogues - """ - return self._proxy.dialogues - - @property - def field_types(self) -> FieldTypeList: - """ - Access the field_types - """ - return self._proxy.field_types - - @property - def model_builds(self) -> ModelBuildList: - """ - Access the model_builds - """ - return self._proxy.model_builds - - @property - def queries(self) -> QueryList: - """ - Access the queries - """ - return self._proxy.queries - - @property - def style_sheet(self) -> StyleSheetList: - """ - Access the style_sheet - """ - return self._proxy.style_sheet - - @property - def tasks(self) -> TaskList: - """ - Access the tasks - """ - return self._proxy.tasks - - @property - def webhooks(self) -> WebhookList: - """ - Access the webhooks - """ - return self._proxy.webhooks - - 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): - def __init__(self, version: Version, sid: str): - """ - Initialize the AssistantContext - - :param version: Version that contains the resource - :param sid: The Twilio-provided string that uniquely identifies the Assistant resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Assistants/{sid}".format(**self._solution) - - self._defaults: Optional[DefaultsList] = None - self._dialogues: Optional[DialogueList] = None - self._field_types: Optional[FieldTypeList] = None - self._model_builds: Optional[ModelBuildList] = None - self._queries: Optional[QueryList] = None - self._style_sheet: Optional[StyleSheetList] = None - self._tasks: Optional[TaskList] = None - self._webhooks: Optional[WebhookList] = None - - def delete(self) -> bool: - """ - Deletes the AssistantInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AssistantInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> AssistantInstance: - """ - Fetch the AssistantInstance - - - :returns: The fetched AssistantInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return AssistantInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> AssistantInstance: - """ - Asynchronous coroutine to fetch the AssistantInstance - - - :returns: The fetched AssistantInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return AssistantInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - defaults: Union[object, object] = values.unset, - development_stage: Union[str, object] = values.unset, - ) -> AssistantInstance: - """ - Update the AssistantInstance - - :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 log_queries: Whether queries should be logged and kept after training. Can be: `true` or `false` and defaults to `true`. If `true`, queries are stored for 30 days, and then deleted. If `false`, no queries are stored. - :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. The first 64 characters must be unique. - :param callback_url: Reserved. - :param callback_events: Reserved. - :param style_sheet: The JSON string that defines the Assistant's [style sheet](https://www.twilio.com/docs/autopilot/api/assistant/stylesheet) - :param defaults: A JSON object that defines the Assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios, including initiation actions and fallback tasks. - :param development_stage: A string describing the state of the assistant. - - :returns: The updated AssistantInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "LogQueries": log_queries, - "UniqueName": unique_name, - "CallbackUrl": callback_url, - "CallbackEvents": callback_events, - "StyleSheet": serialize.object(style_sheet), - "Defaults": serialize.object(defaults), - "DevelopmentStage": development_stage, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - defaults: Union[object, object] = values.unset, - development_stage: Union[str, object] = values.unset, - ) -> AssistantInstance: - """ - Asynchronous coroutine to update the AssistantInstance - - :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 log_queries: Whether queries should be logged and kept after training. Can be: `true` or `false` and defaults to `true`. If `true`, queries are stored for 30 days, and then deleted. If `false`, no queries are stored. - :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. The first 64 characters must be unique. - :param callback_url: Reserved. - :param callback_events: Reserved. - :param style_sheet: The JSON string that defines the Assistant's [style sheet](https://www.twilio.com/docs/autopilot/api/assistant/stylesheet) - :param defaults: A JSON object that defines the Assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios, including initiation actions and fallback tasks. - :param development_stage: A string describing the state of the assistant. - - :returns: The updated AssistantInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "LogQueries": log_queries, - "UniqueName": unique_name, - "CallbackUrl": callback_url, - "CallbackEvents": callback_events, - "StyleSheet": serialize.object(style_sheet), - "Defaults": serialize.object(defaults), - "DevelopmentStage": development_stage, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def defaults(self) -> DefaultsList: - """ - Access the defaults - """ - if self._defaults is None: - self._defaults = DefaultsList( - self._version, - self._solution["sid"], - ) - return self._defaults - - @property - def dialogues(self) -> DialogueList: - """ - Access the dialogues - """ - if self._dialogues is None: - self._dialogues = DialogueList( - self._version, - self._solution["sid"], - ) - return self._dialogues - - @property - def field_types(self) -> FieldTypeList: - """ - Access the field_types - """ - if self._field_types is None: - self._field_types = FieldTypeList( - self._version, - self._solution["sid"], - ) - return self._field_types - - @property - def model_builds(self) -> ModelBuildList: - """ - Access the model_builds - """ - if self._model_builds is None: - self._model_builds = ModelBuildList( - self._version, - self._solution["sid"], - ) - return self._model_builds - - @property - def queries(self) -> QueryList: - """ - Access the queries - """ - if self._queries is None: - self._queries = QueryList( - self._version, - self._solution["sid"], - ) - return self._queries - - @property - def style_sheet(self) -> StyleSheetList: - """ - Access the style_sheet - """ - if self._style_sheet is None: - self._style_sheet = StyleSheetList( - self._version, - self._solution["sid"], - ) - return self._style_sheet - - @property - def tasks(self) -> TaskList: - """ - Access the tasks - """ - if self._tasks is None: - self._tasks = TaskList( - self._version, - self._solution["sid"], - ) - return self._tasks - - @property - def webhooks(self) -> WebhookList: - """ - Access the webhooks - """ - if self._webhooks is None: - self._webhooks = WebhookList( - self._version, - self._solution["sid"], - ) - return self._webhooks - - 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): - def __init__(self, version: Version): - """ - Initialize the AssistantList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Assistants" - - def create( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - defaults: Union[object, object] = values.unset, - ) -> AssistantInstance: - """ - Create the AssistantInstance - - :param friendly_name: A descriptive string that you create to describe the new resource. It is not unique and can be up to 255 characters long. - :param log_queries: Whether queries should be logged and kept after training. Can be: `true` or `false` and defaults to `true`. If `true`, queries are stored for 30 days, and then deleted. If `false`, no queries are stored. - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. The first 64 characters must be unique. - :param callback_url: Reserved. - :param callback_events: Reserved. - :param style_sheet: The JSON string that defines the Assistant's [style sheet](https://www.twilio.com/docs/autopilot/api/assistant/stylesheet) - :param defaults: A JSON object that defines the Assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios, including initiation actions and fallback tasks. - - :returns: The created AssistantInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "LogQueries": log_queries, - "UniqueName": unique_name, - "CallbackUrl": callback_url, - "CallbackEvents": callback_events, - "StyleSheet": serialize.object(style_sheet), - "Defaults": serialize.object(defaults), - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantInstance(self._version, payload) - - async def create_async( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - defaults: Union[object, object] = values.unset, - ) -> AssistantInstance: - """ - Asynchronously create the AssistantInstance - - :param friendly_name: A descriptive string that you create to describe the new resource. It is not unique and can be up to 255 characters long. - :param log_queries: Whether queries should be logged and kept after training. Can be: `true` or `false` and defaults to `true`. If `true`, queries are stored for 30 days, and then deleted. If `false`, no queries are stored. - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. The first 64 characters must be unique. - :param callback_url: Reserved. - :param callback_events: Reserved. - :param style_sheet: The JSON string that defines the Assistant's [style sheet](https://www.twilio.com/docs/autopilot/api/assistant/stylesheet) - :param defaults: A JSON object that defines the Assistant's [default tasks](https://www.twilio.com/docs/autopilot/api/assistant/defaults) for various scenarios, including initiation actions and fallback tasks. - - :returns: The created AssistantInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "LogQueries": log_queries, - "UniqueName": unique_name, - "CallbackUrl": callback_url, - "CallbackEvents": callback_events, - "StyleSheet": serialize.object(style_sheet), - "Defaults": serialize.object(defaults), - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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, sid: str) -> AssistantContext: - """ - Constructs a AssistantContext - - :param sid: The Twilio-provided string that uniquely identifies the Assistant resource to update. - """ - return AssistantContext(self._version, sid=sid) - - def __call__(self, sid: str) -> AssistantContext: - """ - Constructs a AssistantContext - - :param sid: The Twilio-provided string that uniquely identifies the Assistant resource to update. - """ - return AssistantContext(self._version, sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/defaults.py b/twilio/rest/autopilot/v1/assistant/defaults.py deleted file mode 100644 index 0db77b8417..0000000000 --- a/twilio/rest/autopilot/v1/assistant/defaults.py +++ /dev/null @@ -1,273 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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.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 DefaultsInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Defaults resource. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource. - :ivar url: The absolute URL of the Defaults resource. - :ivar data: The JSON string that describes the default task links for the `assistant_initiation`, `collect`, and `fallback` situations. - """ - - def __init__(self, version: Version, payload: Dict[str, Any], assistant_sid: str): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.url: Optional[str] = payload.get("url") - self.data: Optional[Dict[str, object]] = payload.get("data") - - self._solution = { - "assistant_sid": assistant_sid, - } - self._context: Optional[DefaultsContext] = None - - @property - def _proxy(self) -> "DefaultsContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DefaultsContext for this DefaultsInstance - """ - if self._context is None: - self._context = DefaultsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - ) - return self._context - - def fetch(self) -> "DefaultsInstance": - """ - Fetch the DefaultsInstance - - - :returns: The fetched DefaultsInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DefaultsInstance": - """ - Asynchronous coroutine to fetch the DefaultsInstance - - - :returns: The fetched DefaultsInstance - """ - return await self._proxy.fetch_async() - - def update( - self, defaults: Union[object, object] = values.unset - ) -> "DefaultsInstance": - """ - Update the DefaultsInstance - - :param defaults: A JSON string that describes the default task links for the `assistant_initiation`, `collect`, and `fallback` situations. - - :returns: The updated DefaultsInstance - """ - return self._proxy.update( - defaults=defaults, - ) - - async def update_async( - self, defaults: Union[object, object] = values.unset - ) -> "DefaultsInstance": - """ - Asynchronous coroutine to update the DefaultsInstance - - :param defaults: A JSON string that describes the default task links for the `assistant_initiation`, `collect`, and `fallback` situations. - - :returns: The updated DefaultsInstance - """ - return await self._proxy.update_async( - defaults=defaults, - ) - - 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 DefaultsContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the DefaultsContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/Defaults".format(**self._solution) - - def fetch(self) -> DefaultsInstance: - """ - Fetch the DefaultsInstance - - - :returns: The fetched DefaultsInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return DefaultsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - async def fetch_async(self) -> DefaultsInstance: - """ - Asynchronous coroutine to fetch the DefaultsInstance - - - :returns: The fetched DefaultsInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return DefaultsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - def update( - self, defaults: Union[object, object] = values.unset - ) -> DefaultsInstance: - """ - Update the DefaultsInstance - - :param defaults: A JSON string that describes the default task links for the `assistant_initiation`, `collect`, and `fallback` situations. - - :returns: The updated DefaultsInstance - """ - data = values.of( - { - "Defaults": serialize.object(defaults), - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return DefaultsInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def update_async( - self, defaults: Union[object, object] = values.unset - ) -> DefaultsInstance: - """ - Asynchronous coroutine to update the DefaultsInstance - - :param defaults: A JSON string that describes the default task links for the `assistant_initiation`, `collect`, and `fallback` situations. - - :returns: The updated DefaultsInstance - """ - data = values.of( - { - "Defaults": serialize.object(defaults), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return DefaultsInstance( - self._version, payload, assistant_sid=self._solution["assistant_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 DefaultsList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the DefaultsList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to fetch. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - - def get(self) -> DefaultsContext: - """ - Constructs a DefaultsContext - - """ - return DefaultsContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __call__(self) -> DefaultsContext: - """ - Constructs a DefaultsContext - - """ - return DefaultsContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/dialogue.py b/twilio/rest/autopilot/v1/assistant/dialogue.py deleted file mode 100644 index 6e06f4ff2b..0000000000 --- a/twilio/rest/autopilot/v1/assistant/dialogue.py +++ /dev/null @@ -1,210 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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.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 DialogueInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Dialogue resource. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource. - :ivar sid: The unique string that we created to identify the Dialogue resource. - :ivar data: The JSON string that describes the dialogue session object. - :ivar url: The absolute URL of the Dialogue resource. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.data: Optional[Dict[str, object]] = payload.get("data") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[DialogueContext] = None - - @property - def _proxy(self) -> "DialogueContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DialogueContext for this DialogueInstance - """ - if self._context is None: - self._context = DialogueContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def fetch(self) -> "DialogueInstance": - """ - Fetch the DialogueInstance - - - :returns: The fetched DialogueInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DialogueInstance": - """ - Asynchronous coroutine to fetch the DialogueInstance - - - :returns: The fetched DialogueInstance - """ - 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 "".format(context) - - -class DialogueContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the DialogueContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to fetch. - :param sid: The Twilio-provided string that uniquely identifies the Dialogue resource to fetch. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Dialogues/{sid}".format( - **self._solution - ) - - def fetch(self) -> DialogueInstance: - """ - Fetch the DialogueInstance - - - :returns: The fetched DialogueInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return DialogueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> DialogueInstance: - """ - Asynchronous coroutine to fetch the DialogueInstance - - - :returns: The fetched DialogueInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return DialogueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_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 "".format(context) - - -class DialogueList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the DialogueList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to fetch. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - - def get(self, sid: str) -> DialogueContext: - """ - Constructs a DialogueContext - - :param sid: The Twilio-provided string that uniquely identifies the Dialogue resource to fetch. - """ - return DialogueContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> DialogueContext: - """ - Constructs a DialogueContext - - :param sid: The Twilio-provided string that uniquely identifies the Dialogue resource to fetch. - """ - return DialogueContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/field_type/__init__.py b/twilio/rest/autopilot/v1/assistant/field_type/__init__.py deleted file mode 100644 index 4639a6e962..0000000000 --- a/twilio/rest/autopilot/v1/assistant/field_type/__init__.py +++ /dev/null @@ -1,652 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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.autopilot.v1.assistant.field_type.field_value import FieldValueList - - -class FieldTypeInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the FieldType resource. - :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. It is not unique and can be up to 255 characters long. - :ivar links: A list of the URLs of related resources. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource. - :ivar sid: The unique string that we created to identify the FieldType 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. - :ivar url: The absolute URL of the FieldType resource. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.friendly_name: Optional[str] = payload.get("friendly_name") - self.links: Optional[Dict[str, object]] = payload.get("links") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[FieldTypeContext] = None - - @property - def _proxy(self) -> "FieldTypeContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FieldTypeContext for this FieldTypeInstance - """ - if self._context is None: - self._context = FieldTypeContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the FieldTypeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldTypeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "FieldTypeInstance": - """ - Fetch the FieldTypeInstance - - - :returns: The fetched FieldTypeInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "FieldTypeInstance": - """ - Asynchronous coroutine to fetch the FieldTypeInstance - - - :returns: The fetched FieldTypeInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> "FieldTypeInstance": - """ - Update the FieldTypeInstance - - :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 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. The first 64 characters must be unique. - - :returns: The updated FieldTypeInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> "FieldTypeInstance": - """ - Asynchronous coroutine to update the FieldTypeInstance - - :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 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. The first 64 characters must be unique. - - :returns: The updated FieldTypeInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - unique_name=unique_name, - ) - - @property - def field_values(self) -> FieldValueList: - """ - Access the field_values - """ - return self._proxy.field_values - - 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 FieldTypeContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the FieldTypeContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the to update. - :param sid: The Twilio-provided string that uniquely identifies the FieldType resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/FieldTypes/{sid}".format( - **self._solution - ) - - self._field_values: Optional[FieldValueList] = None - - def delete(self) -> bool: - """ - Deletes the FieldTypeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldTypeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> FieldTypeInstance: - """ - Fetch the FieldTypeInstance - - - :returns: The fetched FieldTypeInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> FieldTypeInstance: - """ - Asynchronous coroutine to fetch the FieldTypeInstance - - - :returns: The fetched FieldTypeInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> FieldTypeInstance: - """ - Update the FieldTypeInstance - - :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 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. The first 64 characters must be unique. - - :returns: The updated FieldTypeInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> FieldTypeInstance: - """ - Asynchronous coroutine to update the FieldTypeInstance - - :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 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. The first 64 characters must be unique. - - :returns: The updated FieldTypeInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - @property - def field_values(self) -> FieldValueList: - """ - Access the field_values - """ - if self._field_values is None: - self._field_values = FieldValueList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._field_values - - 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 FieldTypePage(Page): - def get_instance(self, payload: Dict[str, Any]) -> FieldTypeInstance: - """ - Build an instance of FieldTypeInstance - - :param payload: Payload response from the API - """ - return FieldTypeInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class FieldTypeList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the FieldTypeList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resources to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/FieldTypes".format(**self._solution) - - def create( - self, unique_name: str, friendly_name: Union[str, object] = values.unset - ) -> FieldTypeInstance: - """ - Create the FieldTypeInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. The first 64 characters must be unique. - :param friendly_name: A descriptive string that you create to describe the new resource. It is not unique and can be up to 255 characters long. - - :returns: The created FieldTypeInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldTypeInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def create_async( - self, unique_name: str, friendly_name: Union[str, object] = values.unset - ) -> FieldTypeInstance: - """ - Asynchronously create the FieldTypeInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. The first 64 characters must be unique. - :param friendly_name: A descriptive string that you create to describe the new resource. It is not unique and can be up to 255 characters long. - - :returns: The created FieldTypeInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldTypeInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[FieldTypeInstance]: - """ - Streams FieldTypeInstance 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[FieldTypeInstance]: - """ - Asynchronously streams FieldTypeInstance 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[FieldTypeInstance]: - """ - Lists FieldTypeInstance 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[FieldTypeInstance]: - """ - Asynchronously lists FieldTypeInstance 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, - ) -> FieldTypePage: - """ - Retrieve a single page of FieldTypeInstance 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 FieldTypeInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return FieldTypePage(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, - ) -> FieldTypePage: - """ - Asynchronously retrieve a single page of FieldTypeInstance 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 FieldTypeInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return FieldTypePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> FieldTypePage: - """ - Retrieve a specific page of FieldTypeInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldTypeInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return FieldTypePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> FieldTypePage: - """ - Asynchronously retrieve a specific page of FieldTypeInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldTypeInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return FieldTypePage(self._version, response, self._solution) - - def get(self, sid: str) -> FieldTypeContext: - """ - Constructs a FieldTypeContext - - :param sid: The Twilio-provided string that uniquely identifies the FieldType resource to update. - """ - return FieldTypeContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> FieldTypeContext: - """ - Constructs a FieldTypeContext - - :param sid: The Twilio-provided string that uniquely identifies the FieldType resource to update. - """ - return FieldTypeContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/field_type/field_value.py b/twilio/rest/autopilot/v1/assistant/field_type/field_value.py deleted file mode 100644 index 38cb71161f..0000000000 --- a/twilio/rest/autopilot/v1/assistant/field_type/field_value.py +++ /dev/null @@ -1,577 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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 FieldValueInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the FieldValue resource. - :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 field_type_sid: The SID of the Field Type associated with the Field Value. - :ivar language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) tag that specifies the language of the value. Currently supported tags: `en-US` - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the FieldType associated with the resource. - :ivar sid: The unique string that we created to identify the FieldValue resource. - :ivar value: The Field Value data. - :ivar url: The absolute URL of the FieldValue resource. - :ivar synonym_of: The word for which the field value is a synonym of. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - field_type_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.field_type_sid: Optional[str] = payload.get("field_type_sid") - self.language: Optional[str] = payload.get("language") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.value: Optional[str] = payload.get("value") - self.url: Optional[str] = payload.get("url") - self.synonym_of: Optional[str] = payload.get("synonym_of") - - self._solution = { - "assistant_sid": assistant_sid, - "field_type_sid": field_type_sid, - "sid": sid or self.sid, - } - self._context: Optional[FieldValueContext] = None - - @property - def _proxy(self) -> "FieldValueContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FieldValueContext for this FieldValueInstance - """ - if self._context is None: - self._context = FieldValueContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the FieldValueInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldValueInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "FieldValueInstance": - """ - Fetch the FieldValueInstance - - - :returns: The fetched FieldValueInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "FieldValueInstance": - """ - Asynchronous coroutine to fetch the FieldValueInstance - - - :returns: The fetched FieldValueInstance - """ - 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 "".format(context) - - -class FieldValueContext(InstanceContext): - def __init__( - self, version: Version, assistant_sid: str, field_type_sid: str, sid: str - ): - """ - Initialize the FieldValueContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the FieldType associated with the resource to fetch. - :param field_type_sid: The SID of the Field Type associated with the Field Value to fetch. - :param sid: The Twilio-provided string that uniquely identifies the FieldValue resource to fetch. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "field_type_sid": field_type_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/FieldTypes/{field_type_sid}/FieldValues/{sid}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the FieldValueInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldValueInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> FieldValueInstance: - """ - Fetch the FieldValueInstance - - - :returns: The fetched FieldValueInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> FieldValueInstance: - """ - Asynchronous coroutine to fetch the FieldValueInstance - - - :returns: The fetched FieldValueInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_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 "".format(context) - - -class FieldValuePage(Page): - def get_instance(self, payload: Dict[str, Any]) -> FieldValueInstance: - """ - Build an instance of FieldValueInstance - - :param payload: Payload response from the API - """ - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class FieldValueList(ListResource): - def __init__(self, version: Version, assistant_sid: str, field_type_sid: str): - """ - Initialize the FieldValueList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the FieldType associated with the resources to read. - :param field_type_sid: The SID of the Field Type associated with the Field Value to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "field_type_sid": field_type_sid, - } - self._uri = "/Assistants/{assistant_sid}/FieldTypes/{field_type_sid}/FieldValues".format( - **self._solution - ) - - def create( - self, language: str, value: str, synonym_of: Union[str, object] = values.unset - ) -> FieldValueInstance: - """ - Create the FieldValueInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) tag that specifies the language of the value. Currently supported tags: `en-US` - :param value: The Field Value data. - :param synonym_of: The string value that indicates which word the field value is a synonym of. - - :returns: The created FieldValueInstance - """ - data = values.of( - { - "Language": language, - "Value": value, - "SynonymOf": synonym_of, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - ) - - async def create_async( - self, language: str, value: str, synonym_of: Union[str, object] = values.unset - ) -> FieldValueInstance: - """ - Asynchronously create the FieldValueInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) tag that specifies the language of the value. Currently supported tags: `en-US` - :param value: The Field Value data. - :param synonym_of: The string value that indicates which word the field value is a synonym of. - - :returns: The created FieldValueInstance - """ - data = values.of( - { - "Language": language, - "Value": value, - "SynonymOf": synonym_of, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - ) - - def stream( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[FieldValueInstance]: - """ - Streams FieldValueInstance 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 language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) tag that specifies the language of the value. Currently supported tags: `en-US` - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(language=language, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[FieldValueInstance]: - """ - Asynchronously streams FieldValueInstance 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 language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) tag that specifies the language of the value. Currently supported tags: `en-US` - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(language=language, page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[FieldValueInstance]: - """ - Lists FieldValueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) tag that specifies the language of the value. Currently supported tags: `en-US` - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[FieldValueInstance]: - """ - Asynchronously lists FieldValueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) tag that specifies the language of the value. Currently supported tags: `en-US` - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - language: 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, - ) -> FieldValuePage: - """ - Retrieve a single page of FieldValueInstance records from the API. - Request is executed immediately - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) tag that specifies the language of the value. Currently supported tags: `en-US` - :param page_token: PageToken provided by the API - :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 FieldValueInstance - """ - data = values.of( - { - "Language": language, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return FieldValuePage(self._version, response, self._solution) - - async def page_async( - self, - language: 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, - ) -> FieldValuePage: - """ - Asynchronously retrieve a single page of FieldValueInstance records from the API. - Request is executed immediately - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) tag that specifies the language of the value. Currently supported tags: `en-US` - :param page_token: PageToken provided by the API - :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 FieldValueInstance - """ - data = values.of( - { - "Language": language, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return FieldValuePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> FieldValuePage: - """ - Retrieve a specific page of FieldValueInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldValueInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return FieldValuePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> FieldValuePage: - """ - Asynchronously retrieve a specific page of FieldValueInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldValueInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return FieldValuePage(self._version, response, self._solution) - - def get(self, sid: str) -> FieldValueContext: - """ - Constructs a FieldValueContext - - :param sid: The Twilio-provided string that uniquely identifies the FieldValue resource to fetch. - """ - return FieldValueContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - sid=sid, - ) - - def __call__(self, sid: str) -> FieldValueContext: - """ - Constructs a FieldValueContext - - :param sid: The Twilio-provided string that uniquely identifies the FieldValue resource to fetch. - """ - return FieldValueContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - sid=sid, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/model_build.py b/twilio/rest/autopilot/v1/assistant/model_build.py deleted file mode 100644 index ccfb8a1c36..0000000000 --- a/twilio/rest/autopilot/v1/assistant/model_build.py +++ /dev/null @@ -1,627 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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 ModelBuildInstance(InstanceResource): - class Status(object): - ENQUEUED = "enqueued" - BUILDING = "building" - COMPLETED = "completed" - FAILED = "failed" - CANCELED = "canceled" - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ModelBuild resource. - :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 assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource. - :ivar sid: The unique string that we created to identify the ModelBuild resource. - :ivar status: - :ivar 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. - :ivar url: The absolute URL of the ModelBuild resource. - :ivar build_duration: The time in seconds it took to build the model. - :ivar error_code: If the `status` for the model build is `failed`, this value is a code to more information about the failure. This value will be null for all other statuses. See [error code dictionary](https://www.twilio.com/docs/api/errors) for a description of the error. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.status: Optional["ModelBuildInstance.Status"] = payload.get("status") - self.unique_name: Optional[str] = payload.get("unique_name") - self.url: Optional[str] = payload.get("url") - self.build_duration: Optional[int] = deserialize.integer( - payload.get("build_duration") - ) - self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[ModelBuildContext] = None - - @property - def _proxy(self) -> "ModelBuildContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: ModelBuildContext for this ModelBuildInstance - """ - if self._context is None: - self._context = ModelBuildContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the ModelBuildInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ModelBuildInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "ModelBuildInstance": - """ - Fetch the ModelBuildInstance - - - :returns: The fetched ModelBuildInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "ModelBuildInstance": - """ - Asynchronous coroutine to fetch the ModelBuildInstance - - - :returns: The fetched ModelBuildInstance - """ - return await self._proxy.fetch_async() - - def update( - self, unique_name: Union[str, object] = values.unset - ) -> "ModelBuildInstance": - """ - Update the ModelBuildInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be a unique string of no more than 64 characters. It can be used as an alternative to the `sid` in the URL path to address the resource. - - :returns: The updated ModelBuildInstance - """ - return self._proxy.update( - unique_name=unique_name, - ) - - async def update_async( - self, unique_name: Union[str, object] = values.unset - ) -> "ModelBuildInstance": - """ - Asynchronous coroutine to update the ModelBuildInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be a unique string of no more than 64 characters. It can be used as an alternative to the `sid` in the URL path to address the resource. - - :returns: The updated ModelBuildInstance - """ - return await self._proxy.update_async( - unique_name=unique_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 "".format(context) - - -class ModelBuildContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the ModelBuildContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to update. - :param sid: The Twilio-provided string that uniquely identifies the ModelBuild resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/ModelBuilds/{sid}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the ModelBuildInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ModelBuildInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> ModelBuildInstance: - """ - Fetch the ModelBuildInstance - - - :returns: The fetched ModelBuildInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ModelBuildInstance: - """ - Asynchronous coroutine to fetch the ModelBuildInstance - - - :returns: The fetched ModelBuildInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - def update( - self, unique_name: Union[str, object] = values.unset - ) -> ModelBuildInstance: - """ - Update the ModelBuildInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be a unique string of no more than 64 characters. It can be used as an alternative to the `sid` in the URL path to address the resource. - - :returns: The updated ModelBuildInstance - """ - data = values.of( - { - "UniqueName": unique_name, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, unique_name: Union[str, object] = values.unset - ) -> ModelBuildInstance: - """ - Asynchronous coroutine to update the ModelBuildInstance - - :param unique_name: An application-defined string that uniquely identifies the resource. This value must be a unique string of no more than 64 characters. It can be used as an alternative to the `sid` in the URL path to address the resource. - - :returns: The updated ModelBuildInstance - """ - data = values.of( - { - "UniqueName": unique_name, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_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 "".format(context) - - -class ModelBuildPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> ModelBuildInstance: - """ - Build an instance of ModelBuildInstance - - :param payload: Payload response from the API - """ - return ModelBuildInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class ModelBuildList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the ModelBuildList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resources to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/ModelBuilds".format(**self._solution) - - def create( - self, - status_callback: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> ModelBuildInstance: - """ - Create the ModelBuildInstance - - :param status_callback: The URL we should call using a POST method to send status information to your application. - :param unique_name: An application-defined string that uniquely identifies the new resource. This value must be a unique string of no more than 64 characters. It can be used as an alternative to the `sid` in the URL path to address the resource. - - :returns: The created ModelBuildInstance - """ - data = values.of( - { - "StatusCallback": status_callback, - "UniqueName": unique_name, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return ModelBuildInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def create_async( - self, - status_callback: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> ModelBuildInstance: - """ - Asynchronously create the ModelBuildInstance - - :param status_callback: The URL we should call using a POST method to send status information to your application. - :param unique_name: An application-defined string that uniquely identifies the new resource. This value must be a unique string of no more than 64 characters. It can be used as an alternative to the `sid` in the URL path to address the resource. - - :returns: The created ModelBuildInstance - """ - data = values.of( - { - "StatusCallback": status_callback, - "UniqueName": unique_name, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ModelBuildInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[ModelBuildInstance]: - """ - Streams ModelBuildInstance 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[ModelBuildInstance]: - """ - Asynchronously streams ModelBuildInstance 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[ModelBuildInstance]: - """ - Lists ModelBuildInstance 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[ModelBuildInstance]: - """ - Asynchronously lists ModelBuildInstance 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, - ) -> ModelBuildPage: - """ - Retrieve a single page of ModelBuildInstance 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 ModelBuildInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return ModelBuildPage(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, - ) -> ModelBuildPage: - """ - Asynchronously retrieve a single page of ModelBuildInstance 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 ModelBuildInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return ModelBuildPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> ModelBuildPage: - """ - Retrieve a specific page of ModelBuildInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ModelBuildInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return ModelBuildPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> ModelBuildPage: - """ - Asynchronously retrieve a specific page of ModelBuildInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ModelBuildInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return ModelBuildPage(self._version, response, self._solution) - - def get(self, sid: str) -> ModelBuildContext: - """ - Constructs a ModelBuildContext - - :param sid: The Twilio-provided string that uniquely identifies the ModelBuild resource to update. - """ - return ModelBuildContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> ModelBuildContext: - """ - Constructs a ModelBuildContext - - :param sid: The Twilio-provided string that uniquely identifies the ModelBuild resource to update. - """ - return ModelBuildContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/query.py b/twilio/rest/autopilot/v1/assistant/query.py deleted file mode 100644 index 500f6bb7f7..0000000000 --- a/twilio/rest/autopilot/v1/assistant/query.py +++ /dev/null @@ -1,729 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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 QueryInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Query resource. - :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 results: The natural language analysis results that include the [Task](https://www.twilio.com/docs/autopilot/api/task) recognized and a list of identified [Fields](https://www.twilio.com/docs/autopilot/api/task-field). - :ivar language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used by the Query. For example: `en-US`. - :ivar model_build_sid: The SID of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) queried. - :ivar query: The end-user's natural language input. - :ivar sample_sid: The SID of an optional reference to the [Sample](https://www.twilio.com/docs/autopilot/api/task-sample) created from the query. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource. - :ivar sid: The unique string that we created to identify the Query resource. - :ivar status: The status of the Query. Can be: `pending-review`, `reviewed`, or `discarded` - :ivar url: The absolute URL of the Query resource. - :ivar source_channel: The communication channel from where the end-user input came. - :ivar dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.results: Optional[Dict[str, object]] = payload.get("results") - self.language: Optional[str] = payload.get("language") - self.model_build_sid: Optional[str] = payload.get("model_build_sid") - self.query: Optional[str] = payload.get("query") - self.sample_sid: Optional[str] = payload.get("sample_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.status: Optional[str] = payload.get("status") - self.url: Optional[str] = payload.get("url") - self.source_channel: Optional[str] = payload.get("source_channel") - self.dialogue_sid: Optional[str] = payload.get("dialogue_sid") - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[QueryContext] = None - - @property - def _proxy(self) -> "QueryContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: QueryContext for this QueryInstance - """ - if self._context is None: - self._context = QueryContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the QueryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the QueryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "QueryInstance": - """ - Fetch the QueryInstance - - - :returns: The fetched QueryInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "QueryInstance": - """ - Asynchronous coroutine to fetch the QueryInstance - - - :returns: The fetched QueryInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - sample_sid: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - ) -> "QueryInstance": - """ - Update the QueryInstance - - :param sample_sid: The SID of an optional reference to the [Sample](https://www.twilio.com/docs/autopilot/api/task-sample) created from the query. - :param status: The new status of the resource. Can be: `pending-review`, `reviewed`, or `discarded` - - :returns: The updated QueryInstance - """ - return self._proxy.update( - sample_sid=sample_sid, - status=status, - ) - - async def update_async( - self, - sample_sid: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - ) -> "QueryInstance": - """ - Asynchronous coroutine to update the QueryInstance - - :param sample_sid: The SID of an optional reference to the [Sample](https://www.twilio.com/docs/autopilot/api/task-sample) created from the query. - :param status: The new status of the resource. Can be: `pending-review`, `reviewed`, or `discarded` - - :returns: The updated QueryInstance - """ - return await self._proxy.update_async( - sample_sid=sample_sid, - status=status, - ) - - 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 QueryContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the QueryContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to update. - :param sid: The Twilio-provided string that uniquely identifies the Query resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Queries/{sid}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the QueryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the QueryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> QueryInstance: - """ - Fetch the QueryInstance - - - :returns: The fetched QueryInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> QueryInstance: - """ - Asynchronous coroutine to fetch the QueryInstance - - - :returns: The fetched QueryInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - sample_sid: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - ) -> QueryInstance: - """ - Update the QueryInstance - - :param sample_sid: The SID of an optional reference to the [Sample](https://www.twilio.com/docs/autopilot/api/task-sample) created from the query. - :param status: The new status of the resource. Can be: `pending-review`, `reviewed`, or `discarded` - - :returns: The updated QueryInstance - """ - data = values.of( - { - "SampleSid": sample_sid, - "Status": status, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - sample_sid: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - ) -> QueryInstance: - """ - Asynchronous coroutine to update the QueryInstance - - :param sample_sid: The SID of an optional reference to the [Sample](https://www.twilio.com/docs/autopilot/api/task-sample) created from the query. - :param status: The new status of the resource. Can be: `pending-review`, `reviewed`, or `discarded` - - :returns: The updated QueryInstance - """ - data = values.of( - { - "SampleSid": sample_sid, - "Status": status, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_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 "".format(context) - - -class QueryPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> QueryInstance: - """ - Build an instance of QueryInstance - - :param payload: Payload response from the API - """ - return QueryInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class QueryList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the QueryList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resources to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/Queries".format(**self._solution) - - def create( - self, - language: str, - query: str, - tasks: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - ) -> QueryInstance: - """ - Create the QueryInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the new query. For example: `en-US`. - :param query: The end-user's natural language input. It can be up to 2048 characters long. - :param tasks: The list of tasks to limit the new query to. Tasks are expressed as a comma-separated list of task `unique_name` values. For example, `task-unique_name-1, task-unique_name-2`. Listing specific tasks is useful to constrain the paths that a user can take. - :param model_build: The SID or unique name of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) to be queried. - - :returns: The created QueryInstance - """ - data = values.of( - { - "Language": language, - "Query": query, - "Tasks": tasks, - "ModelBuild": model_build, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return QueryInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def create_async( - self, - language: str, - query: str, - tasks: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - ) -> QueryInstance: - """ - Asynchronously create the QueryInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the new query. For example: `en-US`. - :param query: The end-user's natural language input. It can be up to 2048 characters long. - :param tasks: The list of tasks to limit the new query to. Tasks are expressed as a comma-separated list of task `unique_name` values. For example, `task-unique_name-1, task-unique_name-2`. Listing specific tasks is useful to constrain the paths that a user can take. - :param model_build: The SID or unique name of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) to be queried. - - :returns: The created QueryInstance - """ - data = values.of( - { - "Language": language, - "Query": query, - "Tasks": tasks, - "ModelBuild": model_build, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return QueryInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def stream( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - dialogue_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[QueryInstance]: - """ - Streams QueryInstance 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 language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used by the Query resources to read. For example: `en-US`. - :param str model_build: The SID or unique name of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) to be queried. - :param str status: The status of the resources to read. Can be: `pending-review`, `reviewed`, or `discarded` - :param str dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - model_build=model_build, - status=status, - dialogue_sid=dialogue_sid, - page_size=limits["page_size"], - ) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - dialogue_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[QueryInstance]: - """ - Asynchronously streams QueryInstance 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 language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used by the Query resources to read. For example: `en-US`. - :param str model_build: The SID or unique name of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) to be queried. - :param str status: The status of the resources to read. Can be: `pending-review`, `reviewed`, or `discarded` - :param str dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - model_build=model_build, - status=status, - dialogue_sid=dialogue_sid, - page_size=limits["page_size"], - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - dialogue_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[QueryInstance]: - """ - Lists QueryInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used by the Query resources to read. For example: `en-US`. - :param str model_build: The SID or unique name of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) to be queried. - :param str status: The status of the resources to read. Can be: `pending-review`, `reviewed`, or `discarded` - :param str dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - model_build=model_build, - status=status, - dialogue_sid=dialogue_sid, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - dialogue_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[QueryInstance]: - """ - Asynchronously lists QueryInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used by the Query resources to read. For example: `en-US`. - :param str model_build: The SID or unique name of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) to be queried. - :param str status: The status of the resources to read. Can be: `pending-review`, `reviewed`, or `discarded` - :param str dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - model_build=model_build, - status=status, - dialogue_sid=dialogue_sid, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - dialogue_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, - ) -> QueryPage: - """ - Retrieve a single page of QueryInstance records from the API. - Request is executed immediately - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used by the Query resources to read. For example: `en-US`. - :param model_build: The SID or unique name of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) to be queried. - :param status: The status of the resources to read. Can be: `pending-review`, `reviewed`, or `discarded` - :param dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :param page_token: PageToken provided by the API - :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 QueryInstance - """ - data = values.of( - { - "Language": language, - "ModelBuild": model_build, - "Status": status, - "DialogueSid": dialogue_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return QueryPage(self._version, response, self._solution) - - async def page_async( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - dialogue_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, - ) -> QueryPage: - """ - Asynchronously retrieve a single page of QueryInstance records from the API. - Request is executed immediately - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used by the Query resources to read. For example: `en-US`. - :param model_build: The SID or unique name of the [Model Build](https://www.twilio.com/docs/autopilot/api/model-build) to be queried. - :param status: The status of the resources to read. Can be: `pending-review`, `reviewed`, or `discarded` - :param dialogue_sid: The SID of the [Dialogue](https://www.twilio.com/docs/autopilot/api/dialogue). - :param page_token: PageToken provided by the API - :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 QueryInstance - """ - data = values.of( - { - "Language": language, - "ModelBuild": model_build, - "Status": status, - "DialogueSid": dialogue_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return QueryPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> QueryPage: - """ - Retrieve a specific page of QueryInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of QueryInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return QueryPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> QueryPage: - """ - Asynchronously retrieve a specific page of QueryInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of QueryInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return QueryPage(self._version, response, self._solution) - - def get(self, sid: str) -> QueryContext: - """ - Constructs a QueryContext - - :param sid: The Twilio-provided string that uniquely identifies the Query resource to update. - """ - return QueryContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> QueryContext: - """ - Constructs a QueryContext - - :param sid: The Twilio-provided string that uniquely identifies the Query resource to update. - """ - return QueryContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/style_sheet.py b/twilio/rest/autopilot/v1/assistant/style_sheet.py deleted file mode 100644 index 980ab40111..0000000000 --- a/twilio/rest/autopilot/v1/assistant/style_sheet.py +++ /dev/null @@ -1,273 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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.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 StyleSheetInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the StyleSheet resource. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource. - :ivar url: The absolute URL of the StyleSheet resource. - :ivar data: The JSON string that describes the style sheet object. - """ - - def __init__(self, version: Version, payload: Dict[str, Any], assistant_sid: str): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.url: Optional[str] = payload.get("url") - self.data: Optional[Dict[str, object]] = payload.get("data") - - self._solution = { - "assistant_sid": assistant_sid, - } - self._context: Optional[StyleSheetContext] = None - - @property - def _proxy(self) -> "StyleSheetContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: StyleSheetContext for this StyleSheetInstance - """ - if self._context is None: - self._context = StyleSheetContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - ) - return self._context - - def fetch(self) -> "StyleSheetInstance": - """ - Fetch the StyleSheetInstance - - - :returns: The fetched StyleSheetInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "StyleSheetInstance": - """ - Asynchronous coroutine to fetch the StyleSheetInstance - - - :returns: The fetched StyleSheetInstance - """ - return await self._proxy.fetch_async() - - def update( - self, style_sheet: Union[object, object] = values.unset - ) -> "StyleSheetInstance": - """ - Update the StyleSheetInstance - - :param style_sheet: The JSON string that describes the style sheet object. - - :returns: The updated StyleSheetInstance - """ - return self._proxy.update( - style_sheet=style_sheet, - ) - - async def update_async( - self, style_sheet: Union[object, object] = values.unset - ) -> "StyleSheetInstance": - """ - Asynchronous coroutine to update the StyleSheetInstance - - :param style_sheet: The JSON string that describes the style sheet object. - - :returns: The updated StyleSheetInstance - """ - return await self._proxy.update_async( - style_sheet=style_sheet, - ) - - 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 StyleSheetContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the StyleSheetContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/StyleSheet".format(**self._solution) - - def fetch(self) -> StyleSheetInstance: - """ - Fetch the StyleSheetInstance - - - :returns: The fetched StyleSheetInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return StyleSheetInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - async def fetch_async(self) -> StyleSheetInstance: - """ - Asynchronous coroutine to fetch the StyleSheetInstance - - - :returns: The fetched StyleSheetInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return StyleSheetInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - def update( - self, style_sheet: Union[object, object] = values.unset - ) -> StyleSheetInstance: - """ - Update the StyleSheetInstance - - :param style_sheet: The JSON string that describes the style sheet object. - - :returns: The updated StyleSheetInstance - """ - data = values.of( - { - "StyleSheet": serialize.object(style_sheet), - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return StyleSheetInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def update_async( - self, style_sheet: Union[object, object] = values.unset - ) -> StyleSheetInstance: - """ - Asynchronous coroutine to update the StyleSheetInstance - - :param style_sheet: The JSON string that describes the style sheet object. - - :returns: The updated StyleSheetInstance - """ - data = values.of( - { - "StyleSheet": serialize.object(style_sheet), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return StyleSheetInstance( - self._version, payload, assistant_sid=self._solution["assistant_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 StyleSheetList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the StyleSheetList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to fetch. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - - def get(self) -> StyleSheetContext: - """ - Constructs a StyleSheetContext - - """ - return StyleSheetContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __call__(self) -> StyleSheetContext: - """ - Constructs a StyleSheetContext - - """ - return StyleSheetContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/task/__init__.py b/twilio/rest/autopilot/v1/assistant/task/__init__.py deleted file mode 100644 index c90b412acf..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/__init__.py +++ /dev/null @@ -1,758 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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.autopilot.v1.assistant.task.field import FieldList -from twilio.rest.autopilot.v1.assistant.task.sample import SampleList -from twilio.rest.autopilot.v1.assistant.task.task_actions import TaskActionsList -from twilio.rest.autopilot.v1.assistant.task.task_statistics import TaskStatisticsList - - -class TaskInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Task resource. - :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. It is not unique and can be up to 255 characters long. - :ivar links: A list of the URLs of related resources. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource. - :ivar sid: The unique string that we created to identify the Task 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. - :ivar actions_url: The URL from which the Assistant can fetch actions. - :ivar url: The absolute URL of the Task resource. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.friendly_name: Optional[str] = payload.get("friendly_name") - self.links: Optional[Dict[str, object]] = payload.get("links") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.actions_url: Optional[str] = payload.get("actions_url") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[TaskContext] = None - - @property - def _proxy(self) -> "TaskContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: TaskContext for this TaskInstance - """ - if self._context is None: - self._context = TaskContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the TaskInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the TaskInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "TaskInstance": - """ - Fetch the TaskInstance - - - :returns: The fetched TaskInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "TaskInstance": - """ - Asynchronous coroutine to fetch the TaskInstance - - - :returns: The fetched TaskInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> "TaskInstance": - """ - Update the TaskInstance - - :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 unique_name: An application-defined string that uniquely identifies the resource. This value must be 64 characters or less in length and be unique. It can be used as an alternative to the `sid` in the URL path to address the resource. - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. - :param actions_url: The URL from which the Assistant can fetch actions. - - :returns: The updated TaskInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - actions=actions, - actions_url=actions_url, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> "TaskInstance": - """ - Asynchronous coroutine to update the TaskInstance - - :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 unique_name: An application-defined string that uniquely identifies the resource. This value must be 64 characters or less in length and be unique. It can be used as an alternative to the `sid` in the URL path to address the resource. - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. - :param actions_url: The URL from which the Assistant can fetch actions. - - :returns: The updated TaskInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - unique_name=unique_name, - actions=actions, - actions_url=actions_url, - ) - - @property - def fields(self) -> FieldList: - """ - Access the fields - """ - return self._proxy.fields - - @property - def samples(self) -> SampleList: - """ - Access the samples - """ - return self._proxy.samples - - @property - def task_actions(self) -> TaskActionsList: - """ - Access the task_actions - """ - return self._proxy.task_actions - - @property - def statistics(self) -> TaskStatisticsList: - """ - Access the statistics - """ - return self._proxy.statistics - - 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 TaskContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the TaskContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to update. - :param sid: The Twilio-provided string that uniquely identifies the Task resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{sid}".format(**self._solution) - - self._fields: Optional[FieldList] = None - self._samples: Optional[SampleList] = None - self._task_actions: Optional[TaskActionsList] = None - self._statistics: Optional[TaskStatisticsList] = None - - def delete(self) -> bool: - """ - Deletes the TaskInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the TaskInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> TaskInstance: - """ - Fetch the TaskInstance - - - :returns: The fetched TaskInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> TaskInstance: - """ - Asynchronous coroutine to fetch the TaskInstance - - - :returns: The fetched TaskInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> TaskInstance: - """ - Update the TaskInstance - - :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 unique_name: An application-defined string that uniquely identifies the resource. This value must be 64 characters or less in length and be unique. It can be used as an alternative to the `sid` in the URL path to address the resource. - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. - :param actions_url: The URL from which the Assistant can fetch actions. - - :returns: The updated TaskInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Actions": serialize.object(actions), - "ActionsUrl": actions_url, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> TaskInstance: - """ - Asynchronous coroutine to update the TaskInstance - - :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 unique_name: An application-defined string that uniquely identifies the resource. This value must be 64 characters or less in length and be unique. It can be used as an alternative to the `sid` in the URL path to address the resource. - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. - :param actions_url: The URL from which the Assistant can fetch actions. - - :returns: The updated TaskInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Actions": serialize.object(actions), - "ActionsUrl": actions_url, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - @property - def fields(self) -> FieldList: - """ - Access the fields - """ - if self._fields is None: - self._fields = FieldList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._fields - - @property - def samples(self) -> SampleList: - """ - Access the samples - """ - if self._samples is None: - self._samples = SampleList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._samples - - @property - def task_actions(self) -> TaskActionsList: - """ - Access the task_actions - """ - if self._task_actions is None: - self._task_actions = TaskActionsList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._task_actions - - @property - def statistics(self) -> TaskStatisticsList: - """ - Access the statistics - """ - if self._statistics is None: - self._statistics = TaskStatisticsList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._statistics - - 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 TaskPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> TaskInstance: - """ - Build an instance of TaskInstance - - :param payload: Payload response from the API - """ - return TaskInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class TaskList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the TaskList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resources to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks".format(**self._solution) - - def create( - self, - unique_name: str, - friendly_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> TaskInstance: - """ - Create the TaskInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. This value must be unique and 64 characters or less in length. - :param friendly_name: A descriptive string that you create to describe the new resource. It is not unique and can be up to 255 characters long. - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. It is optional and not unique. - :param actions_url: The URL from which the Assistant can fetch actions. - - :returns: The created TaskInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - "Actions": serialize.object(actions), - "ActionsUrl": actions_url, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def create_async( - self, - unique_name: str, - friendly_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> TaskInstance: - """ - Asynchronously create the TaskInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. This value must be unique and 64 characters or less in length. - :param friendly_name: A descriptive string that you create to describe the new resource. It is not unique and can be up to 255 characters long. - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. It is optional and not unique. - :param actions_url: The URL from which the Assistant can fetch actions. - - :returns: The created TaskInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - "Actions": serialize.object(actions), - "ActionsUrl": actions_url, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def stream( - self, - 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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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[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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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[TaskInstance]: - """ - Lists TaskInstance 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[TaskInstance]: - """ - Asynchronously lists TaskInstance 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, - ) -> TaskPage: - """ - Retrieve a single page of TaskInstance 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 TaskInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return TaskPage(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, - ) -> TaskPage: - """ - Asynchronously retrieve a single page of TaskInstance 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 TaskInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return TaskPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> TaskPage: - """ - Retrieve a specific page of TaskInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of TaskInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return TaskPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> TaskPage: - """ - Asynchronously retrieve a specific page of TaskInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of TaskInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return TaskPage(self._version, response, self._solution) - - def get(self, sid: str) -> TaskContext: - """ - Constructs a TaskContext - - :param sid: The Twilio-provided string that uniquely identifies the Task resource to update. - """ - return TaskContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> TaskContext: - """ - Constructs a TaskContext - - :param sid: The Twilio-provided string that uniquely identifies the Task resource to update. - """ - return TaskContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/task/field.py b/twilio/rest/autopilot/v1/assistant/task/field.py deleted file mode 100644 index dc48c44659..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/field.py +++ /dev/null @@ -1,549 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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 FieldInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Field resource. - :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 field_type: The Field Type of the field. Can be: a [Built-in Field Type](https://www.twilio.com/docs/autopilot/built-in-field-types), the unique_name, or the SID of a custom Field Type. - :ivar task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource associated with this Field. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task associated with the resource. - :ivar sid: The unique string that we created to identify the Field 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. - :ivar url: The absolute URL of the Field resource. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - task_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.field_type: Optional[str] = payload.get("field_type") - self.task_sid: Optional[str] = payload.get("task_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - "sid": sid or self.sid, - } - self._context: Optional[FieldContext] = None - - @property - def _proxy(self) -> "FieldContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FieldContext for this FieldInstance - """ - if self._context is None: - self._context = FieldContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the FieldInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "FieldInstance": - """ - Fetch the FieldInstance - - - :returns: The fetched FieldInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "FieldInstance": - """ - Asynchronous coroutine to fetch the FieldInstance - - - :returns: The fetched FieldInstance - """ - 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 "".format(context) - - -class FieldContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, task_sid: str, sid: str): - """ - Initialize the FieldContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task associated with the resource to fetch. - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource associated with the Field resource to fetch. - :param sid: The Twilio-provided string that uniquely identifies the Field resource to fetch. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Fields/{sid}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the FieldInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> FieldInstance: - """ - Fetch the FieldInstance - - - :returns: The fetched FieldInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> FieldInstance: - """ - Asynchronous coroutine to fetch the FieldInstance - - - :returns: The fetched FieldInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_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 "".format(context) - - -class FieldPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> FieldInstance: - """ - Build an instance of FieldInstance - - :param payload: Payload response from the API - """ - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class FieldList(ListResource): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the FieldList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task associated with the resources to read. - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) resource associated with the Field resources to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Fields".format( - **self._solution - ) - - def create(self, field_type: str, unique_name: str) -> FieldInstance: - """ - Create the FieldInstance - - :param field_type: The Field Type of the new field. Can be: a [Built-in Field Type](https://www.twilio.com/docs/autopilot/built-in-field-types), the `unique_name`, or the `sid` of a custom Field Type. - :param unique_name: An application-defined string that uniquely identifies the new resource. This value must be a unique string of no more than 64 characters. It can be used as an alternative to the `sid` in the URL path to address the resource. - - :returns: The created FieldInstance - """ - data = values.of( - { - "FieldType": field_type, - "UniqueName": unique_name, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def create_async(self, field_type: str, unique_name: str) -> FieldInstance: - """ - Asynchronously create the FieldInstance - - :param field_type: The Field Type of the new field. Can be: a [Built-in Field Type](https://www.twilio.com/docs/autopilot/built-in-field-types), the `unique_name`, or the `sid` of a custom Field Type. - :param unique_name: An application-defined string that uniquely identifies the new resource. This value must be a unique string of no more than 64 characters. It can be used as an alternative to the `sid` in the URL path to address the resource. - - :returns: The created FieldInstance - """ - data = values.of( - { - "FieldType": field_type, - "UniqueName": unique_name, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[FieldInstance]: - """ - Streams FieldInstance 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[FieldInstance]: - """ - Asynchronously streams FieldInstance 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[FieldInstance]: - """ - Lists FieldInstance 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[FieldInstance]: - """ - Asynchronously lists FieldInstance 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, - ) -> FieldPage: - """ - Retrieve a single page of FieldInstance 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 FieldInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return FieldPage(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, - ) -> FieldPage: - """ - Asynchronously retrieve a single page of FieldInstance 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 FieldInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return FieldPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> FieldPage: - """ - Retrieve a specific page of FieldInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return FieldPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> FieldPage: - """ - Asynchronously retrieve a specific page of FieldInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return FieldPage(self._version, response, self._solution) - - def get(self, sid: str) -> FieldContext: - """ - Constructs a FieldContext - - :param sid: The Twilio-provided string that uniquely identifies the Field resource to fetch. - """ - return FieldContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=sid, - ) - - def __call__(self, sid: str) -> FieldContext: - """ - Constructs a FieldContext - - :param sid: The Twilio-provided string that uniquely identifies the Field resource to fetch. - """ - return FieldContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=sid, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/task/sample.py b/twilio/rest/autopilot/v1/assistant/task/sample.py deleted file mode 100644 index ce413aeaa1..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/sample.py +++ /dev/null @@ -1,697 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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 SampleInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sample resource. - :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 task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) associated with the resource. - :ivar language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task associated with the resource. - :ivar sid: The unique string that we created to identify the Sample resource. - :ivar tagged_text: The text example of how end users might express the task. The sample can contain [Field tag blocks](https://www.twilio.com/docs/autopilot/api/task-sample#field-tagging). - :ivar url: The absolute URL of the Sample resource. - :ivar source_channel: The communication channel from which the sample was captured. Can be: `voice`, `sms`, `chat`, `alexa`, `google-assistant`, `slack`, or null if not included. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - task_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.task_sid: Optional[str] = payload.get("task_sid") - self.language: Optional[str] = payload.get("language") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.tagged_text: Optional[str] = payload.get("tagged_text") - self.url: Optional[str] = payload.get("url") - self.source_channel: Optional[str] = payload.get("source_channel") - - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - "sid": sid or self.sid, - } - self._context: Optional[SampleContext] = None - - @property - def _proxy(self) -> "SampleContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SampleContext for this SampleInstance - """ - if self._context is None: - self._context = SampleContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the SampleInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SampleInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "SampleInstance": - """ - Fetch the SampleInstance - - - :returns: The fetched SampleInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SampleInstance": - """ - Asynchronous coroutine to fetch the SampleInstance - - - :returns: The fetched SampleInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - language: Union[str, object] = values.unset, - tagged_text: Union[str, object] = values.unset, - source_channel: Union[str, object] = values.unset, - ) -> "SampleInstance": - """ - Update the SampleInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param tagged_text: The text example of how end users might express the task. The sample can contain [Field tag blocks](https://www.twilio.com/docs/autopilot/api/task-sample#field-tagging). - :param source_channel: The communication channel from which the sample was captured. Can be: `voice`, `sms`, `chat`, `alexa`, `google-assistant`, `slack`, or null if not included. - - :returns: The updated SampleInstance - """ - return self._proxy.update( - language=language, - tagged_text=tagged_text, - source_channel=source_channel, - ) - - async def update_async( - self, - language: Union[str, object] = values.unset, - tagged_text: Union[str, object] = values.unset, - source_channel: Union[str, object] = values.unset, - ) -> "SampleInstance": - """ - Asynchronous coroutine to update the SampleInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param tagged_text: The text example of how end users might express the task. The sample can contain [Field tag blocks](https://www.twilio.com/docs/autopilot/api/task-sample#field-tagging). - :param source_channel: The communication channel from which the sample was captured. Can be: `voice`, `sms`, `chat`, `alexa`, `google-assistant`, `slack`, or null if not included. - - :returns: The updated SampleInstance - """ - return await self._proxy.update_async( - language=language, - tagged_text=tagged_text, - source_channel=source_channel, - ) - - 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 SampleContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, task_sid: str, sid: str): - """ - Initialize the SampleContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task associated with the resource to update. - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) associated with the Sample resource to update. - :param sid: The Twilio-provided string that uniquely identifies the Sample resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples/{sid}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the SampleInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SampleInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> SampleInstance: - """ - Fetch the SampleInstance - - - :returns: The fetched SampleInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> SampleInstance: - """ - Asynchronous coroutine to fetch the SampleInstance - - - :returns: The fetched SampleInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - language: Union[str, object] = values.unset, - tagged_text: Union[str, object] = values.unset, - source_channel: Union[str, object] = values.unset, - ) -> SampleInstance: - """ - Update the SampleInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param tagged_text: The text example of how end users might express the task. The sample can contain [Field tag blocks](https://www.twilio.com/docs/autopilot/api/task-sample#field-tagging). - :param source_channel: The communication channel from which the sample was captured. Can be: `voice`, `sms`, `chat`, `alexa`, `google-assistant`, `slack`, or null if not included. - - :returns: The updated SampleInstance - """ - data = values.of( - { - "Language": language, - "TaggedText": tagged_text, - "SourceChannel": source_channel, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - language: Union[str, object] = values.unset, - tagged_text: Union[str, object] = values.unset, - source_channel: Union[str, object] = values.unset, - ) -> SampleInstance: - """ - Asynchronous coroutine to update the SampleInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param tagged_text: The text example of how end users might express the task. The sample can contain [Field tag blocks](https://www.twilio.com/docs/autopilot/api/task-sample#field-tagging). - :param source_channel: The communication channel from which the sample was captured. Can be: `voice`, `sms`, `chat`, `alexa`, `google-assistant`, `slack`, or null if not included. - - :returns: The updated SampleInstance - """ - data = values.of( - { - "Language": language, - "TaggedText": tagged_text, - "SourceChannel": source_channel, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_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 "".format(context) - - -class SamplePage(Page): - def get_instance(self, payload: Dict[str, Any]) -> SampleInstance: - """ - Build an instance of SampleInstance - - :param payload: Payload response from the API - """ - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class SampleList(ListResource): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the SampleList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task associated with the resources to read. - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) associated with the Sample resources to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples".format( - **self._solution - ) - - def create( - self, - language: str, - tagged_text: str, - source_channel: Union[str, object] = values.unset, - ) -> SampleInstance: - """ - Create the SampleInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the new sample. For example: `en-US`. - :param tagged_text: The text example of how end users might express the task. The sample can contain [Field tag blocks](https://www.twilio.com/docs/autopilot/api/task-sample#field-tagging). - :param source_channel: The communication channel from which the new sample was captured. Can be: `voice`, `sms`, `chat`, `alexa`, `google-assistant`, `slack`, or null if not included. - - :returns: The created SampleInstance - """ - data = values.of( - { - "Language": language, - "TaggedText": tagged_text, - "SourceChannel": source_channel, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def create_async( - self, - language: str, - tagged_text: str, - source_channel: Union[str, object] = values.unset, - ) -> SampleInstance: - """ - Asynchronously create the SampleInstance - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the new sample. For example: `en-US`. - :param tagged_text: The text example of how end users might express the task. The sample can contain [Field tag blocks](https://www.twilio.com/docs/autopilot/api/task-sample#field-tagging). - :param source_channel: The communication channel from which the new sample was captured. Can be: `voice`, `sms`, `chat`, `alexa`, `google-assistant`, `slack`, or null if not included. - - :returns: The created SampleInstance - """ - data = values.of( - { - "Language": language, - "TaggedText": tagged_text, - "SourceChannel": source_channel, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def stream( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SampleInstance]: - """ - Streams SampleInstance 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 language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(language=language, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SampleInstance]: - """ - Asynchronously streams SampleInstance 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 language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(language=language, page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SampleInstance]: - """ - Lists SampleInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SampleInstance]: - """ - Asynchronously lists SampleInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - language: 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, - ) -> SamplePage: - """ - Retrieve a single page of SampleInstance records from the API. - Request is executed immediately - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param page_token: PageToken provided by the API - :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 SampleInstance - """ - data = values.of( - { - "Language": language, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return SamplePage(self._version, response, self._solution) - - async def page_async( - self, - language: 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, - ) -> SamplePage: - """ - Asynchronously retrieve a single page of SampleInstance records from the API. - Request is executed immediately - - :param language: The [ISO language-country](https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html) string that specifies the language used for the sample. For example: `en-US`. - :param page_token: PageToken provided by the API - :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 SampleInstance - """ - data = values.of( - { - "Language": language, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return SamplePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> SamplePage: - """ - Retrieve a specific page of SampleInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SampleInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return SamplePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> SamplePage: - """ - Asynchronously retrieve a specific page of SampleInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SampleInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return SamplePage(self._version, response, self._solution) - - def get(self, sid: str) -> SampleContext: - """ - Constructs a SampleContext - - :param sid: The Twilio-provided string that uniquely identifies the Sample resource to update. - """ - return SampleContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=sid, - ) - - def __call__(self, sid: str) -> SampleContext: - """ - Constructs a SampleContext - - :param sid: The Twilio-provided string that uniquely identifies the Sample resource to update. - """ - return SampleContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=sid, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/task/task_actions.py b/twilio/rest/autopilot/v1/assistant/task/task_actions.py deleted file mode 100644 index 01d4efa2c1..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/task_actions.py +++ /dev/null @@ -1,301 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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.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 TaskActionsInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskActions resource. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task associated with the resource. - :ivar task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) associated with the resource. - :ivar url: The absolute URL of the TaskActions resource. - :ivar data: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - task_sid: str, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.task_sid: Optional[str] = payload.get("task_sid") - self.url: Optional[str] = payload.get("url") - self.data: Optional[Dict[str, object]] = payload.get("data") - - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._context: Optional[TaskActionsContext] = None - - @property - def _proxy(self) -> "TaskActionsContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: TaskActionsContext for this TaskActionsInstance - """ - if self._context is None: - self._context = TaskActionsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - return self._context - - def fetch(self) -> "TaskActionsInstance": - """ - Fetch the TaskActionsInstance - - - :returns: The fetched TaskActionsInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "TaskActionsInstance": - """ - Asynchronous coroutine to fetch the TaskActionsInstance - - - :returns: The fetched TaskActionsInstance - """ - return await self._proxy.fetch_async() - - def update( - self, actions: Union[object, object] = values.unset - ) -> "TaskActionsInstance": - """ - Update the TaskActionsInstance - - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. - - :returns: The updated TaskActionsInstance - """ - return self._proxy.update( - actions=actions, - ) - - async def update_async( - self, actions: Union[object, object] = values.unset - ) -> "TaskActionsInstance": - """ - Asynchronous coroutine to update the TaskActionsInstance - - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. - - :returns: The updated TaskActionsInstance - """ - return await self._proxy.update_async( - actions=actions, - ) - - 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 TaskActionsContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the TaskActionsContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task for which the task actions to update were defined. - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) for which the task actions to update were defined. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Actions".format( - **self._solution - ) - - def fetch(self) -> TaskActionsInstance: - """ - Fetch the TaskActionsInstance - - - :returns: The fetched TaskActionsInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def fetch_async(self) -> TaskActionsInstance: - """ - Asynchronous coroutine to fetch the TaskActionsInstance - - - :returns: The fetched TaskActionsInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def update( - self, actions: Union[object, object] = values.unset - ) -> TaskActionsInstance: - """ - Update the TaskActionsInstance - - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. - - :returns: The updated TaskActionsInstance - """ - data = values.of( - { - "Actions": serialize.object(actions), - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def update_async( - self, actions: Union[object, object] = values.unset - ) -> TaskActionsInstance: - """ - Asynchronous coroutine to update the TaskActionsInstance - - :param actions: The JSON string that specifies the [actions](https://www.twilio.com/docs/autopilot/actions) that instruct the Assistant on how to perform the task. - - :returns: The updated TaskActionsInstance - """ - data = values.of( - { - "Actions": serialize.object(actions), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_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 TaskActionsList(ListResource): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the TaskActionsList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task for which the task actions to fetch were defined. - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) for which the task actions to fetch were defined. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - - def get(self) -> TaskActionsContext: - """ - Constructs a TaskActionsContext - - """ - return TaskActionsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __call__(self) -> TaskActionsContext: - """ - Constructs a TaskActionsContext - - """ - return TaskActionsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/task/task_statistics.py b/twilio/rest/autopilot/v1/assistant/task/task_statistics.py deleted file mode 100644 index 3d92b05cb9..0000000000 --- a/twilio/rest/autopilot/v1/assistant/task/task_statistics.py +++ /dev/null @@ -1,221 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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 deserialize -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 TaskStatisticsInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskStatistics resource. - :ivar assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the Task associated with the resource. - :ivar task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) for which the statistics were collected. - :ivar samples_count: The total number of [Samples](https://www.twilio.com/docs/autopilot/api/task-sample) associated with the Task. - :ivar fields_count: The total number of [Fields](https://www.twilio.com/docs/autopilot/api/task-field) associated with the Task. - :ivar url: The absolute URL of the TaskStatistics resource. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - task_sid: str, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.task_sid: Optional[str] = payload.get("task_sid") - self.samples_count: Optional[int] = deserialize.integer( - payload.get("samples_count") - ) - self.fields_count: Optional[int] = deserialize.integer( - payload.get("fields_count") - ) - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._context: Optional[TaskStatisticsContext] = None - - @property - def _proxy(self) -> "TaskStatisticsContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: TaskStatisticsContext for this TaskStatisticsInstance - """ - if self._context is None: - self._context = TaskStatisticsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - return self._context - - def fetch(self) -> "TaskStatisticsInstance": - """ - Fetch the TaskStatisticsInstance - - - :returns: The fetched TaskStatisticsInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "TaskStatisticsInstance": - """ - Asynchronous coroutine to fetch the TaskStatisticsInstance - - - :returns: The fetched TaskStatisticsInstance - """ - 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 "".format(context) - - -class TaskStatisticsContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the TaskStatisticsContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to fetch. - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) that is associated with the resource to fetch. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Statistics".format( - **self._solution - ) - - def fetch(self) -> TaskStatisticsInstance: - """ - Fetch the TaskStatisticsInstance - - - :returns: The fetched TaskStatisticsInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return TaskStatisticsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def fetch_async(self) -> TaskStatisticsInstance: - """ - Asynchronous coroutine to fetch the TaskStatisticsInstance - - - :returns: The fetched TaskStatisticsInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return TaskStatisticsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_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 TaskStatisticsList(ListResource): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the TaskStatisticsList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to fetch. - :param task_sid: The SID of the [Task](https://www.twilio.com/docs/autopilot/api/task) that is associated with the resource to fetch. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - - def get(self) -> TaskStatisticsContext: - """ - Constructs a TaskStatisticsContext - - """ - return TaskStatisticsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __call__(self) -> TaskStatisticsContext: - """ - Constructs a TaskStatisticsContext - - """ - return TaskStatisticsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/assistant/webhook.py b/twilio/rest/autopilot/v1/assistant/webhook.py deleted file mode 100644 index 8a3e3da2f6..0000000000 --- a/twilio/rest/autopilot/v1/assistant/webhook.py +++ /dev/null @@ -1,671 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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 WebhookInstance(InstanceResource): - - """ - :ivar url: The absolute URL of the Webhook resource. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Webhook resource. - :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 assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource. - :ivar sid: The unique string that we created to identify the Webhook 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. - :ivar events: The list of space-separated events that this Webhook is subscribed to. - :ivar webhook_url: The URL associated with this Webhook. - :ivar webhook_method: The method used when calling the webhook's URL. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.url: Optional[str] = payload.get("url") - self.account_sid: Optional[str] = payload.get("account_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.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.events: Optional[str] = payload.get("events") - self.webhook_url: Optional[str] = payload.get("webhook_url") - self.webhook_method: Optional[str] = payload.get("webhook_method") - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[WebhookContext] = None - - @property - def _proxy(self) -> "WebhookContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: WebhookContext for this WebhookInstance - """ - if self._context is None: - self._context = WebhookContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the WebhookInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the WebhookInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "WebhookInstance": - """ - Fetch the WebhookInstance - - - :returns: The fetched WebhookInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "WebhookInstance": - """ - Asynchronous coroutine to fetch the WebhookInstance - - - :returns: The fetched WebhookInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - unique_name: Union[str, object] = values.unset, - events: Union[str, object] = values.unset, - webhook_url: Union[str, object] = values.unset, - webhook_method: Union[str, object] = values.unset, - ) -> "WebhookInstance": - """ - Update the WebhookInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. This value must be unique and 64 characters or less in length. - :param events: The list of space-separated events that this Webhook will subscribe to. - :param webhook_url: The URL associated with this Webhook. - :param webhook_method: The method to be used when calling the webhook's URL. - - :returns: The updated WebhookInstance - """ - return self._proxy.update( - unique_name=unique_name, - events=events, - webhook_url=webhook_url, - webhook_method=webhook_method, - ) - - async def update_async( - self, - unique_name: Union[str, object] = values.unset, - events: Union[str, object] = values.unset, - webhook_url: Union[str, object] = values.unset, - webhook_method: Union[str, object] = values.unset, - ) -> "WebhookInstance": - """ - Asynchronous coroutine to update the WebhookInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. This value must be unique and 64 characters or less in length. - :param events: The list of space-separated events that this Webhook will subscribe to. - :param webhook_url: The URL associated with this Webhook. - :param webhook_method: The method to be used when calling the webhook's URL. - - :returns: The updated WebhookInstance - """ - return await self._proxy.update_async( - unique_name=unique_name, - events=events, - webhook_url=webhook_url, - webhook_method=webhook_method, - ) - - 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 WebhookContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the WebhookContext - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resource to update. - :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Webhooks/{sid}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the WebhookInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the WebhookInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> WebhookInstance: - """ - Fetch the WebhookInstance - - - :returns: The fetched WebhookInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return WebhookInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> WebhookInstance: - """ - Asynchronous coroutine to fetch the WebhookInstance - - - :returns: The fetched WebhookInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return WebhookInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - unique_name: Union[str, object] = values.unset, - events: Union[str, object] = values.unset, - webhook_url: Union[str, object] = values.unset, - webhook_method: Union[str, object] = values.unset, - ) -> WebhookInstance: - """ - Update the WebhookInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. This value must be unique and 64 characters or less in length. - :param events: The list of space-separated events that this Webhook will subscribe to. - :param webhook_url: The URL associated with this Webhook. - :param webhook_method: The method to be used when calling the webhook's URL. - - :returns: The updated WebhookInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "Events": events, - "WebhookUrl": webhook_url, - "WebhookMethod": webhook_method, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return WebhookInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - unique_name: Union[str, object] = values.unset, - events: Union[str, object] = values.unset, - webhook_url: Union[str, object] = values.unset, - webhook_method: Union[str, object] = values.unset, - ) -> WebhookInstance: - """ - Asynchronous coroutine to update the WebhookInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. This value must be unique and 64 characters or less in length. - :param events: The list of space-separated events that this Webhook will subscribe to. - :param webhook_url: The URL associated with this Webhook. - :param webhook_method: The method to be used when calling the webhook's URL. - - :returns: The updated WebhookInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "Events": events, - "WebhookUrl": webhook_url, - "WebhookMethod": webhook_method, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return WebhookInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_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 "".format(context) - - -class WebhookPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: - """ - Build an instance of WebhookInstance - - :param payload: Payload response from the API - """ - return WebhookInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class WebhookList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the WebhookList - - :param version: Version that contains the resource - :param assistant_sid: The SID of the [Assistant](https://www.twilio.com/docs/autopilot/api/assistant) that is the parent of the resources to read. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/Webhooks".format(**self._solution) - - def create( - self, - unique_name: str, - events: str, - webhook_url: str, - webhook_method: Union[str, object] = values.unset, - ) -> WebhookInstance: - """ - Create the WebhookInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. This value must be unique and 64 characters or less in length. - :param events: The list of space-separated events that this Webhook will subscribe to. - :param webhook_url: The URL associated with this Webhook. - :param webhook_method: The method to be used when calling the webhook's URL. - - :returns: The created WebhookInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "Events": events, - "WebhookUrl": webhook_url, - "WebhookMethod": webhook_method, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return WebhookInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def create_async( - self, - unique_name: str, - events: str, - webhook_url: str, - webhook_method: Union[str, object] = values.unset, - ) -> WebhookInstance: - """ - Asynchronously create the WebhookInstance - - :param unique_name: An application-defined string that uniquely identifies the new resource. It can be used as an alternative to the `sid` in the URL path to address the resource. This value must be unique and 64 characters or less in length. - :param events: The list of space-separated events that this Webhook will subscribe to. - :param webhook_url: The URL associated with this Webhook. - :param webhook_method: The method to be used when calling the webhook's URL. - - :returns: The created WebhookInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "Events": events, - "WebhookUrl": webhook_url, - "WebhookMethod": webhook_method, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return WebhookInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[WebhookInstance]: - """ - Streams WebhookInstance 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[WebhookInstance]: - """ - Asynchronously streams WebhookInstance 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[WebhookInstance]: - """ - Lists WebhookInstance 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[WebhookInstance]: - """ - Asynchronously lists WebhookInstance 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, - ) -> WebhookPage: - """ - Retrieve a single page of WebhookInstance 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 WebhookInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return WebhookPage(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, - ) -> WebhookPage: - """ - Asynchronously retrieve a single page of WebhookInstance 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 WebhookInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return WebhookPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> WebhookPage: - """ - Retrieve a specific page of WebhookInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of WebhookInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return WebhookPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> WebhookPage: - """ - Asynchronously retrieve a specific page of WebhookInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of WebhookInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return WebhookPage(self._version, response, self._solution) - - def get(self, sid: str) -> WebhookContext: - """ - Constructs a WebhookContext - - :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. - """ - return WebhookContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> WebhookContext: - """ - Constructs a WebhookContext - - :param sid: The Twilio-provided string that uniquely identifies the Webhook resource to update. - """ - return WebhookContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/autopilot/v1/restore_assistant.py b/twilio/rest/autopilot/v1/restore_assistant.py deleted file mode 100644 index aae8dd3f8f..0000000000 --- a/twilio/rest/autopilot/v1/restore_assistant.py +++ /dev/null @@ -1,136 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Autopilot - 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.instance_resource import InstanceResource -from twilio.base.list_resource import ListResource -from twilio.base.version import Version - - -class RestoreAssistantInstance(InstanceResource): - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Assistant resource. - :ivar sid: The unique string that we created to identify the Assistant resource. - :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 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. - :ivar friendly_name: The string that you assigned to describe the resource. It is not unique and can be up to 255 characters long. - :ivar needs_model_build: Whether model needs to be rebuilt. - :ivar latest_model_build_sid: Reserved. - :ivar log_queries: Whether queries should be logged and kept after training. Can be: `true` or `false` and defaults to `true`. If `true`, queries are stored for 30 days, and then deleted. If `false`, no queries are stored. - :ivar development_stage: A string describing the state of the assistant. - :ivar callback_url: Reserved. - :ivar callback_events: Reserved. - """ - - def __init__(self, version: Version, payload: Dict[str, Any]): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.sid: Optional[str] = payload.get("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.unique_name: Optional[str] = payload.get("unique_name") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.needs_model_build: Optional[bool] = payload.get("needs_model_build") - self.latest_model_build_sid: Optional[str] = payload.get( - "latest_model_build_sid" - ) - self.log_queries: Optional[bool] = payload.get("log_queries") - self.development_stage: Optional[str] = payload.get("development_stage") - self.callback_url: Optional[str] = payload.get("callback_url") - self.callback_events: Optional[str] = payload.get("callback_events") - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class RestoreAssistantList(ListResource): - def __init__(self, version: Version): - """ - Initialize the RestoreAssistantList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Assistants/Restore" - - def update(self, assistant: str) -> RestoreAssistantInstance: - """ - Update the RestoreAssistantInstance - - :param assistant: The Twilio-provided string that uniquely identifies the Assistant resource to restore. - - :returns: The created RestoreAssistantInstance - """ - data = values.of( - { - "Assistant": assistant, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return RestoreAssistantInstance(self._version, payload) - - async def update_async(self, assistant: str) -> RestoreAssistantInstance: - """ - Asynchronously update the RestoreAssistantInstance - - :param assistant: The Twilio-provided string that uniquely identifies the Assistant resource to restore. - - :returns: The created RestoreAssistantInstance - """ - data = values.of( - { - "Assistant": assistant, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return RestoreAssistantInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/bulkexports/BulkexportsBase.py b/twilio/rest/bulkexports/BulkexportsBase.py index d2efe642b4..cbca4c53e4 100644 --- a/twilio/rest/bulkexports/BulkexportsBase.py +++ b/twilio/rest/bulkexports/BulkexportsBase.py @@ -17,6 +17,7 @@ class BulkexportsBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Bulkexports Domain diff --git a/twilio/rest/bulkexports/v1/__init__.py b/twilio/rest/bulkexports/v1/__init__.py index e25eb3afc3..a888fb484f 100644 --- a/twilio/rest/bulkexports/v1/__init__.py +++ b/twilio/rest/bulkexports/v1/__init__.py @@ -20,6 +20,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Bulkexports diff --git a/twilio/rest/bulkexports/v1/export/__init__.py b/twilio/rest/bulkexports/v1/export/__init__.py index 03d6c449ea..2bb449d2a4 100644 --- a/twilio/rest/bulkexports/v1/export/__init__.py +++ b/twilio/rest/bulkexports/v1/export/__init__.py @@ -12,8 +12,9 @@ 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 @@ -25,7 +26,6 @@ class ExportInstance(InstanceResource): - """ :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants :ivar url: The URL of this resource. @@ -47,6 +47,7 @@ def __init__( self._solution = { "resource_type": resource_type or self.resource_type, } + self._context: Optional[ExportContext] = None @property @@ -82,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: """ @@ -107,6 +126,7 @@ def __repr__(self) -> str: class ExportContext(InstanceContext): + def __init__(self, version: Version, resource_type: str): """ Initialize the ExportContext @@ -125,6 +145,22 @@ def __init__(self, version: Version, resource_type: str): self._days: Optional[DayList] = None self._export_custom_jobs: Optional[ExportCustomJobList] = None + 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) -> ExportInstance: """ Fetch the ExportInstance @@ -132,17 +168,43 @@ def fetch(self) -> ExportInstance: :returns: The fetched ExportInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], ) - return ExportInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExportInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExportInstance: """ @@ -151,17 +213,27 @@ async def fetch_async(self) -> ExportInstance: :returns: The fetched ExportInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ExportInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], ) - return ExportInstance( + 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: @@ -198,6 +270,7 @@ def __repr__(self) -> str: class ExportList(ListResource): + def __init__(self, version: Version): """ Initialize the ExportList diff --git a/twilio/rest/bulkexports/v1/export/day.py b/twilio/rest/bulkexports/v1/export/day.py index 26daf02ed1..b19395fde5 100644 --- a/twilio/rest/bulkexports/v1/export/day.py +++ b/twilio/rest/bulkexports/v1/export/day.py @@ -12,9 +12,9 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,7 +23,6 @@ class DayInstance(InstanceResource): - """ :ivar redirect_to: :ivar day: The ISO 8601 format date of the resources in the file, for a UTC day @@ -53,6 +52,7 @@ def __init__( "resource_type": resource_type, "day": day or self.day, } + self._context: Optional[DayContext] = None @property @@ -89,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 @@ -100,6 +118,7 @@ def __repr__(self) -> str: class DayContext(InstanceContext): + def __init__(self, version: Version, resource_type: str, day: str): """ Initialize the DayContext @@ -117,6 +136,22 @@ def __init__(self, version: Version, resource_type: str, day: str): } self._uri = "/Exports/{resource_type}/Days/{day}".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) -> DayInstance: """ Fetch the DayInstance @@ -124,18 +159,45 @@ def fetch(self) -> DayInstance: :returns: The fetched DayInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], ) - return DayInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DayInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> DayInstance: """ @@ -144,18 +206,29 @@ async def fetch_async(self) -> DayInstance: :returns: The fetched DayInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return DayInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], + day=self._solution["day"], ) - return DayInstance( + 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: """ @@ -168,12 +241,14 @@ def __repr__(self) -> str: class DayPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> DayInstance: """ Build an instance of DayInstance :param payload: Payload response from the API """ + return DayInstance( self._version, payload, resource_type=self._solution["resource_type"] ) @@ -188,6 +263,7 @@ def __repr__(self) -> str: class DayList(ListResource): + def __init__(self, version: Version, resource_type: str): """ Initialize the DayList @@ -254,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, @@ -273,6 +399,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -299,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( @@ -307,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, @@ -331,8 +509,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DayPage(self._version, response, self._solution) + 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 DayPage(self._version, response, solution=self._solution) async def page_async( self, @@ -358,10 +542,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return DayPage(self._version, response, self._solution) + 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: """ @@ -373,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: """ @@ -385,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 2c571489d6..dee11094c1 100644 --- a/twilio/rest/bulkexports/v1/export/export_custom_job.py +++ b/twilio/rest/bulkexports/v1/export/export_custom_job.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class ExportCustomJobInstance(InstanceResource): - """ :ivar friendly_name: The friendly name specified when creating the job :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants @@ -49,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" @@ -70,12 +69,14 @@ def __repr__(self) -> str: class ExportCustomJobPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ExportCustomJobInstance: """ Build an instance of ExportCustomJobInstance :param payload: Payload response from the API """ + return ExportCustomJobInstance( self._version, payload, resource_type=self._solution["resource_type"] ) @@ -90,6 +91,7 @@ def __repr__(self) -> str: class ExportCustomJobList(ListResource): + def __init__(self, version: Version, resource_type: str): """ Initialize the ExportCustomJobList @@ -106,6 +108,42 @@ def __init__(self, version: Version, resource_type: str): } self._uri = "/Exports/{resource_type}/Jobs".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "StartDay": start_day, + "EndDay": end_day, + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + "Email": email, + } + ) + 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, start_day: str, @@ -127,6 +165,68 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "StartDay": start_day, @@ -137,15 +237,14 @@ def create( "Email": email, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ExportCustomJobInstance( - self._version, payload, resource_type=self._solution["resource_type"] + 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( @@ -169,26 +268,51 @@ async def create_async( :returns: The created ExportCustomJobInstance """ - data = values.of( - { - "StartDay": start_day, - "EndDay": end_day, - "FriendlyName": friendly_name, - "WebhookUrl": webhook_url, - "WebhookMethod": webhook_method, - "Email": email, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return ExportCustomJobInstance( + self._version, payload, resource_type=self._solution["resource_type"] ) - return ExportCustomJobInstance( + 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, @@ -240,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, @@ -259,6 +433,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -285,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( @@ -293,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, @@ -317,8 +543,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ExportCustomJobPage(self._version, response, self._solution) + 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 ExportCustomJobPage(self._version, response, solution=self._solution) async def page_async( self, @@ -344,10 +576,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ExportCustomJobPage(self._version, response, self._solution) + 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: """ @@ -359,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: """ @@ -371,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 64c3c0f46f..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 @@ -21,7 +22,6 @@ class JobInstance(InstanceResource): - """ :ivar resource_type: The type of communication – Messages, Calls, Conferences, and Participants :ivar friendly_name: The friendly name specified when creating the job @@ -44,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") @@ -60,6 +60,7 @@ def __init__( self._solution = { "job_sid": job_sid or self.job_sid, } + self._context: Optional[JobContext] = None @property @@ -95,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 @@ -113,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 @@ -124,6 +161,7 @@ def __repr__(self) -> str: class JobContext(InstanceContext): + def __init__(self, version: Version, job_sid: str): """ Initialize the JobContext @@ -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,9 +198,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -158,9 +232,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the JobInstance 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) -> JobInstance: @@ -170,17 +268,43 @@ def fetch(self) -> JobInstance: :returns: The fetched JobInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], ) - return JobInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the JobInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> JobInstance: """ @@ -189,17 +313,27 @@ async def fetch_async(self) -> JobInstance: :returns: The fetched JobInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return JobInstance( + self._version, + payload, + job_sid=self._solution["job_sid"], ) - return JobInstance( + 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: """ @@ -212,6 +346,7 @@ def __repr__(self) -> str: class JobList(ListResource): + def __init__(self, version: Version): """ Initialize the JobList diff --git a/twilio/rest/bulkexports/v1/export_configuration.py b/twilio/rest/bulkexports/v1/export_configuration.py index 28e64c5cdc..d5b684b092 100644 --- a/twilio/rest/bulkexports/v1/export_configuration.py +++ b/twilio/rest/bulkexports/v1/export_configuration.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, Optional, Union -from twilio.base import values +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 @@ -22,7 +22,6 @@ class ExportConfigurationInstance(InstanceResource): - """ :ivar enabled: If true, Twilio will automatically generate every day's file when the day is over. :ivar webhook_url: Stores the URL destination for the method specified in webhook_method. @@ -48,6 +47,7 @@ def __init__( self._solution = { "resource_type": resource_type or self.resource_type, } + self._context: Optional[ExportConfigurationContext] = None @property @@ -83,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, @@ -125,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 @@ -136,6 +196,7 @@ def __repr__(self) -> str: class ExportConfigurationContext(InstanceContext): + def __init__(self, version: Version, resource_type: str): """ Initialize the ExportConfigurationContext @@ -151,6 +212,22 @@ def __init__(self, version: Version, resource_type: str): } self._uri = "/Exports/{resource_type}/Configuration".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) -> ExportConfigurationInstance: """ Fetch the ExportConfigurationInstance @@ -158,17 +235,43 @@ def fetch(self) -> ExportConfigurationInstance: :returns: The fetched ExportConfigurationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], ) - return ExportConfigurationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExportConfigurationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExportConfigurationInstance: """ @@ -177,17 +280,57 @@ async def fetch_async(self) -> ExportConfigurationInstance: :returns: The fetched ExportConfigurationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ExportConfigurationInstance( + self._version, + payload, + resource_type=self._solution["resource_type"], ) - return ExportConfigurationInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Enabled": serialize.boolean_to_string(enabled), + "WebhookUrl": webhook_url, + "WebhookMethod": webhook_method, + } + ) + 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, @@ -204,22 +347,64 @@ def update( :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"] + ) + + 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 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 = 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( { - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "WebhookUrl": webhook_url, "WebhookMethod": webhook_method, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ExportConfigurationInstance( - self._version, payload, resource_type=self._solution["resource_type"] + 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( @@ -237,23 +422,35 @@ async def update_async( :returns: The updated ExportConfigurationInstance """ - data = values.of( - { - "Enabled": enabled, - "WebhookUrl": webhook_url, - "WebhookMethod": webhook_method, - } + payload, _, _ = await self._update_async( + enabled=enabled, webhook_url=webhook_url, webhook_method=webhook_method ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return ExportConfigurationInstance( + self._version, payload, resource_type=self._solution["resource_type"] ) - return ExportConfigurationInstance( + 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: """ @@ -266,6 +463,7 @@ def __repr__(self) -> str: class ExportConfigurationList(ListResource): + def __init__(self, version: Version): """ Initialize the ExportConfigurationList diff --git a/twilio/rest/chat/ChatBase.py b/twilio/rest/chat/ChatBase.py index a84b4eb334..6d8656da17 100644 --- a/twilio/rest/chat/ChatBase.py +++ b/twilio/rest/chat/ChatBase.py @@ -19,6 +19,7 @@ class ChatBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Chat Domain diff --git a/twilio/rest/chat/v1/__init__.py b/twilio/rest/chat/v1/__init__.py index f01101f7da..d0ade9eed5 100644 --- a/twilio/rest/chat/v1/__init__.py +++ b/twilio/rest/chat/v1/__init__.py @@ -20,6 +20,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Chat diff --git a/twilio/rest/chat/v1/credential.py b/twilio/rest/chat/v1/credential.py index ecdf1d58e2..a5d48dc68b 100644 --- a/twilio/rest/chat/v1/credential.py +++ b/twilio/rest/chat/v1/credential.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class CredentialInstance(InstanceResource): + class PushService(object): GCM = "gcm" APN = "apn" @@ -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 @@ -185,6 +283,7 @@ def __repr__(self) -> str: class CredentialContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CredentialContext @@ -200,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 @@ -207,9 +320,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -219,9 +354,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance 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) -> CredentialInstance: @@ -231,17 +390,43 @@ def fetch(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialInstance: """ @@ -250,17 +435,63 @@ async def fetch_async(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + 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, + 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 update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def update( self, @@ -283,24 +514,83 @@ def update( :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( { "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -323,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -353,12 +666,14 @@ def __repr__(self) -> str: 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: @@ -371,6 +686,7 @@ def __repr__(self) -> str: class CredentialList(ListResource): + def __init__(self, version: Version): """ Initialize the CredentialList @@ -382,6 +698,44 @@ def __init__(self, version: Version): self._uri = "/Credentials" + def _create( + 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 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.PushService", @@ -405,25 +759,89 @@ def create( :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( { "Type": type, "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(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, @@ -448,25 +866,51 @@ async def create_async( :returns: The created CredentialInstance """ - data = values.of( - { - "Type": type, - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload) + :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, @@ -518,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, @@ -537,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -563,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( @@ -571,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, @@ -595,7 +1141,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CredentialPage(self._version, response) async def page_async( @@ -622,11 +1174,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 f8a377057c..2d4c6b097d 100644 --- a/twilio/rest/chat/v1/service/__init__.py +++ b/twilio/rest/chat/v1/service/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ 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/api/rest/account) that created the Service resource. @@ -96,6 +95,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -131,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 @@ -149,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, @@ -497,120 +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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, @@ -666,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. @@ -725,76 +648,66 @@ 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 """ - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": read_status_enabled, - "ReachabilityEnabled": reachability_enabled, - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": notifications_new_message_enabled, - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": notifications_added_to_channel_enabled, - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": notifications_removed_from_channel_enabled, - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": 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 = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, ) - 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, @@ -850,9 +763,9 @@ async def update_async( 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: """ - 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. 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. @@ -909,29 +822,863 @@ async def update_async( :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 """ - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": read_status_enabled, - "ReachabilityEnabled": reachability_enabled, - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": notifications_new_message_enabled, - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": notifications_added_to_channel_enabled, - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": notifications_removed_from_channel_enabled, - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": notifications_invited_to_channel_enabled, - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, + 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, @@ -969,14 +1716,366 @@ async def update_async( "Limits.UserChannels": limits_user_channels, } ) + 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, + 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: + """ + 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 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, _, _ = 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"]) + + 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 + + :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, + :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: @@ -1025,12 +2124,14 @@ def __repr__(self) -> str: 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: @@ -1043,6 +2144,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -1054,50 +2156,100 @@ 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 - - :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 ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_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, + 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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -1148,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, @@ -1167,6 +2369,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1193,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( @@ -1201,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, @@ -1225,7 +2479,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -1252,11 +2512,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 e04d95a433..d65a59603b 100644 --- a/twilio/rest/chat/v1/service/channel/__init__.py +++ b/twilio/rest/chat/v1/service/channel/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,6 +27,7 @@ class ChannelInstance(InstanceResource): + class ChannelType(object): PUBLIC = "public" PRIVATE = "private" @@ -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: """ @@ -212,6 +292,7 @@ def __repr__(self) -> str: class ChannelContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the ChannelContext @@ -233,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 @@ -240,9 +335,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -252,9 +369,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance 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) -> ChannelInstance: @@ -264,18 +405,45 @@ def fetch(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ChannelInstance: """ @@ -284,34 +452,43 @@ async def fetch_async(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ChannelInstance( + 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( + 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 - - :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. + Internal helper for update operation - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -319,13 +496,34 @@ def update( "Attributes": attributes, } ) + 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, + 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, @@ -333,21 +531,45 @@ 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( { "FriendlyName": friendly_name, @@ -355,13 +577,34 @@ async def update_async( "Attributes": attributes, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -369,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: """ @@ -419,12 +688,14 @@ def __repr__(self) -> str: class ChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ Build an instance of ChannelInstance :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -439,6 +710,7 @@ def __repr__(self) -> str: class ChannelList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the ChannelList @@ -455,6 +727,38 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + 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, @@ -472,6 +776,58 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, @@ -480,15 +836,14 @@ def create( "Type": type, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ChannelInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -508,24 +863,43 @@ async def create_async( :returns: The created ChannelInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Attributes": attributes, - "Type": type, - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return ChannelInstance( + 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, @@ -581,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, @@ -602,6 +1032,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -631,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( @@ -640,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, @@ -667,8 +1155,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ChannelPage(self._version, response, self._solution) + 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 ChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -697,10 +1191,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ChannelPage(self._version, response, self._solution) + 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: """ @@ -712,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: """ @@ -724,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 e3dbbae07f..d88124ec63 100644 --- a/twilio/rest/chat/v1/service/channel/invite.py +++ b/twilio/rest/chat/v1/service/channel/invite.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class InviteInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Invite resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Invite resource. @@ -68,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -105,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 @@ -123,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 @@ -134,6 +170,7 @@ def __repr__(self) -> str: class InviteContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the InviteContext @@ -157,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 @@ -164,9 +215,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -176,9 +249,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance 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) -> InviteInstance: @@ -188,19 +285,47 @@ def fetch(self) -> InviteInstance: :returns: The fetched InviteInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return InviteInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> InviteInstance: """ @@ -209,19 +334,31 @@ async def fetch_async(self) -> InviteInstance: :returns: The fetched InviteInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return InviteInstance( + 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: """ @@ -234,12 +371,14 @@ def __repr__(self) -> str: class InvitePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: """ Build an instance of InviteInstance :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -257,6 +396,7 @@ def __repr__(self) -> str: class InviteList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the InviteList @@ -277,30 +417,44 @@ 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( { "Identity": identity, "RoleSid": role_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -308,30 +462,66 @@ 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( { "Identity": identity, "RoleSid": role_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, + 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, @@ -339,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, @@ -393,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, @@ -414,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -443,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( @@ -452,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, @@ -479,8 +805,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return InvitePage(self._version, response, self._solution) + 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 InvitePage(self._version, response, solution=self._solution) async def page_async( self, @@ -509,10 +841,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return InvitePage(self._version, response, self._solution) + 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: """ @@ -524,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: """ @@ -536,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 62e3912bf9..392847cb06 100644 --- a/twilio/rest/chat/v1/service/channel/member.py +++ b/twilio/rest/chat/v1/service/channel/member.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class MemberInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Member resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the Member resource. @@ -64,9 +63,9 @@ def __init__( self.last_consumed_message_index: Optional[int] = deserialize.integer( payload.get("last_consumed_message_index") ) - self.last_consumption_timestamp: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) self.url: Optional[str] = payload.get("url") self._solution = { @@ -74,6 +73,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -111,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 @@ -129,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, @@ -165,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 @@ -176,6 +248,7 @@ def __repr__(self) -> str: class MemberContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the MemberContext @@ -199,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 @@ -206,9 +293,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -218,9 +327,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance 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) -> MemberInstance: @@ -230,19 +363,47 @@ def fetch(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MemberInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MemberInstance: """ @@ -251,46 +412,76 @@ async def fetch_async(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MemberInstance( + 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( + 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( { "RoleSid": role_sid, "LastConsumedMessageIndex": last_consumed_message_index, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -299,32 +490,75 @@ 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( { "RoleSid": role_sid, "LastConsumedMessageIndex": last_consumed_message_index, } ) + 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, + 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, @@ -333,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 @@ -344,12 +603,14 @@ def __repr__(self) -> str: class MemberPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: """ Build an instance of MemberInstance :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -367,6 +628,7 @@ def __repr__(self) -> str: class MemberList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the MemberList @@ -387,30 +649,44 @@ 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( { "Identity": identity, "RoleSid": role_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -418,30 +694,66 @@ 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( { "Identity": identity, "RoleSid": role_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -449,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, @@ -503,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, @@ -524,6 +914,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -553,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( @@ -562,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, @@ -589,8 +1037,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MemberPage(self._version, response, self._solution) + 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 MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -619,10 +1073,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MemberPage(self._version, response, self._solution) + 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: """ @@ -634,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: """ @@ -646,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 ad45b6eb59..11824c42ed 100644 --- a/twilio/rest/chat/v1/service/channel/message.py +++ b/twilio/rest/chat/v1/service/channel/message.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class MessageInstance(InstanceResource): + class OrderType(object): ASC = "asc" DESC = "desc" @@ -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 @@ -179,6 +253,7 @@ def __repr__(self) -> str: class MessageContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the MessageContext @@ -202,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 @@ -209,9 +298,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -221,9 +332,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance 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) -> MessageInstance: @@ -233,19 +368,47 @@ def fetch(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MessageInstance: """ @@ -254,46 +417,74 @@ async def fetch_async(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + 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( + 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( { "Body": body, "Attributes": attributes, } ) + 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, + 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, @@ -302,32 +493,71 @@ 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( { "Body": body, "Attributes": attributes, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -336,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 @@ -347,12 +602,14 @@ def __repr__(self) -> str: 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, @@ -370,6 +627,7 @@ def __repr__(self) -> str: class MessageList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the MessageList @@ -390,21 +648,19 @@ 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( { "Body": body, @@ -412,13 +668,32 @@ def create( "Attributes": attributes, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -426,21 +701,45 @@ 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( { "Body": body, @@ -448,13 +747,34 @@ async def create_async( "Attributes": attributes, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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: 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, @@ -462,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, @@ -516,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, @@ -537,6 +939,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -566,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( @@ -575,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, @@ -602,8 +1062,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MessagePage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -632,10 +1098,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MessagePage(self._version, response, self._solution) + 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: """ @@ -647,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: """ @@ -659,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 e1a5e5cd53..a17f74eb7c 100644 --- a/twilio/rest/chat/v1/service/role.py +++ b/twilio/rest/chat/v1/service/role.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class RoleInstance(InstanceResource): + class RoleType(object): CHANNEL = "channel" DEPLOYMENT = "deployment" @@ -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 @@ -156,6 +218,7 @@ def __repr__(self) -> str: class RoleContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the RoleContext @@ -173,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 @@ -180,9 +257,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -192,9 +291,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance 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) -> RoleInstance: @@ -204,18 +327,45 @@ def fetch(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return RoleInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RoleInstance: """ @@ -224,12 +374,7 @@ async def fetch_async(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -237,26 +382,54 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -264,26 +437,55 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -291,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 @@ -302,12 +521,14 @@ def __repr__(self) -> str: class RolePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: """ Build an instance of RoleInstance :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -322,6 +543,7 @@ def __repr__(self) -> str: class RoleList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the RoleList @@ -338,6 +560,33 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: 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.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: @@ -350,6 +599,43 @@ def create( :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"] + ) + + 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` and are described in the documentation. + + :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( { "FriendlyName": friendly_name, @@ -357,15 +643,14 @@ def create( "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RoleInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -380,23 +665,32 @@ async def create_async( :returns: The created RoleInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Permission": serialize.map(permission, lambda e: e), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return RoleInstance( + 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, @@ -448,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, @@ -467,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -493,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( @@ -501,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, @@ -525,8 +921,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RolePage(self._version, response, self._solution) + 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 RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -552,10 +954,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RolePage(self._version, response, self._solution) + 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: """ @@ -567,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: """ @@ -579,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 fd6e9d6c44..69a785ce4f 100644 --- a/twilio/rest/chat/v1/service/user/__init__.py +++ b/twilio/rest/chat/v1/service/user/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class UserInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the User resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/api/rest/account) that created the User resource. @@ -77,6 +76,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -113,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 @@ -131,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, @@ -173,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: """ @@ -191,6 +269,7 @@ def __repr__(self) -> str: class UserContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the UserContext @@ -210,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 @@ -217,9 +310,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -229,9 +344,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch(self) -> UserInstance: @@ -241,18 +380,45 @@ def fetch(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserInstance: """ @@ -261,34 +427,43 @@ async def fetch_async(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + 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( + 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( { "RoleSid": role_sid, @@ -296,13 +471,34 @@ def update( "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -310,21 +506,45 @@ 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( { "RoleSid": role_sid, @@ -332,13 +552,34 @@ async def update_async( "FriendlyName": friendly_name, } ) + 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, + 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, @@ -346,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: """ @@ -370,12 +637,14 @@ def __repr__(self) -> str: 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, service_sid=self._solution["service_sid"] ) @@ -390,6 +659,7 @@ def __repr__(self) -> str: class UserList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the UserList @@ -406,6 +676,38 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Users".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + 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, identity: str, @@ -423,6 +725,58 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "Identity": identity, @@ -431,15 +785,14 @@ def create( "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return UserInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -459,24 +812,43 @@ async def create_async( :returns: The created UserInstance """ - data = values.of( - { - "Identity": identity, - "RoleSid": role_sid, - "Attributes": attributes, - "FriendlyName": friendly_name, - } + payload, _, _ = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return UserInstance( + 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, @@ -528,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, @@ -547,6 +969,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -573,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( @@ -581,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, @@ -605,8 +1079,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserPage(self._version, response, self._solution) + 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 UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -632,10 +1112,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserPage(self._version, response, self._solution) + 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: """ @@ -647,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: """ @@ -659,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 353f6bf68f..604cbddec5 100644 --- a/twilio/rest/chat/v1/service/user/user_channel.py +++ b/twilio/rest/chat/v1/service/user/user_channel.py @@ -12,9 +12,9 @@ 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 @@ -23,6 +23,7 @@ class UserChannelInstance(InstanceResource): + class ChannelStatus(object): JOINED = "joined" INVITED = "invited" @@ -75,12 +76,14 @@ def __repr__(self) -> str: class UserChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: """ Build an instance of UserChannelInstance :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -98,6 +101,7 @@ def __repr__(self) -> str: class UserChannelList(ListResource): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ Initialize the UserChannelList @@ -168,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, @@ -187,6 +241,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -213,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( @@ -221,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, @@ -245,8 +351,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserChannelPage(self._version, response, self._solution) + 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 UserChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -272,10 +384,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserChannelPage(self._version, response, self._solution) + 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: """ @@ -287,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: """ @@ -299,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/__init__.py b/twilio/rest/chat/v2/__init__.py index c433e8543f..e949532d56 100644 --- a/twilio/rest/chat/v2/__init__.py +++ b/twilio/rest/chat/v2/__init__.py @@ -20,6 +20,7 @@ class V2(Version): + def __init__(self, domain: Domain): """ Initialize the V2 version of Chat diff --git a/twilio/rest/chat/v2/credential.py b/twilio/rest/chat/v2/credential.py index 4a3df30e93..40c972a9c2 100644 --- a/twilio/rest/chat/v2/credential.py +++ b/twilio/rest/chat/v2/credential.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class CredentialInstance(InstanceResource): + class PushService(object): GCM = "gcm" APN = "apn" @@ -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 @@ -185,6 +283,7 @@ def __repr__(self) -> str: class CredentialContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CredentialContext @@ -200,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 @@ -207,9 +320,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -219,9 +354,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance 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) -> CredentialInstance: @@ -231,17 +390,43 @@ def fetch(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialInstance: """ @@ -250,17 +435,63 @@ async def fetch_async(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + 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, + 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 update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def update( self, @@ -283,24 +514,83 @@ def update( :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( { "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -323,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -353,12 +666,14 @@ def __repr__(self) -> str: 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: @@ -371,6 +686,7 @@ def __repr__(self) -> str: class CredentialList(ListResource): + def __init__(self, version: Version): """ Initialize the CredentialList @@ -382,6 +698,44 @@ def __init__(self, version: Version): self._uri = "/Credentials" + def _create( + 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 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.PushService", @@ -405,25 +759,89 @@ def create( :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( { "Type": type, "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(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, @@ -448,25 +866,51 @@ async def create_async( :returns: The created CredentialInstance """ - data = values.of( - { - "Type": type, - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload) + :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, @@ -518,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, @@ -537,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -563,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( @@ -571,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, @@ -595,7 +1141,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CredentialPage(self._version, response) async def page_async( @@ -622,11 +1174,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 208805c7b7..de0bab251a 100644 --- a/twilio/rest/chat/v2/service/__init__.py +++ b/twilio/rest/chat/v2/service/__init__.py @@ -12,10 +12,10 @@ 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 @@ -28,7 +28,6 @@ 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. @@ -105,6 +104,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -140,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 @@ -158,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, @@ -372,128 +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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, @@ -528,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. @@ -564,53 +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": read_status_enabled, - "ReachabilityEnabled": reachability_enabled, - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": notifications_new_message_enabled, - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.NewMessage.Sound": notifications_new_message_sound, - "Notifications.NewMessage.BadgeCountEnabled": notifications_new_message_badge_count_enabled, - "Notifications.AddedToChannel.Enabled": notifications_added_to_channel_enabled, - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, - "Notifications.RemovedFromChannel.Enabled": notifications_removed_from_channel_enabled, - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, - "Notifications.InvitedToChannel.Enabled": 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": notifications_log_enabled, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, @@ -645,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. @@ -681,75 +586,921 @@ 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 - """ - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultServiceRoleSid": default_service_role_sid, - "DefaultChannelRoleSid": default_channel_role_sid, - "DefaultChannelCreatorRoleSid": default_channel_creator_role_sid, - "ReadStatusEnabled": read_status_enabled, - "ReachabilityEnabled": reachability_enabled, - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": notifications_new_message_enabled, - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.NewMessage.Sound": notifications_new_message_sound, - "Notifications.NewMessage.BadgeCountEnabled": notifications_new_message_badge_count_enabled, - "Notifications.AddedToChannel.Enabled": notifications_added_to_channel_enabled, - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, - "Notifications.RemovedFromChannel.Enabled": notifications_removed_from_channel_enabled, - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, - "Notifications.InvitedToChannel.Enabled": 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": notifications_log_enabled, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def bindings(self) -> BindingList: - """ - Access the bindings - """ - if self._bindings is None: - self._bindings = BindingList( - self._version, - self._solution["sid"], - ) - return self._bindings - - @property - def channels(self) -> ChannelList: + :returns: ApiResponse with instance, status code, and headers """ - Access the channels - """ - if self._channels is None: - self._channels = ChannelList( - self._version, - self._solution["sid"], - ) - return self._channels + 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 + ), + "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 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`. + + :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, + ) + 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, + self._solution["sid"], + ) + return self._bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels @property def roles(self) -> RoleList: @@ -786,12 +1537,14 @@ def __repr__(self) -> str: 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: @@ -804,6 +1557,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -815,50 +1569,100 @@ 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 - - :param friendly_name: A descriptive string that you create to describe the new resource. + Internal helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_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, + 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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -909,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, @@ -928,6 +1782,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -954,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( @@ -962,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, @@ -986,7 +1892,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -1013,11 +1925,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 424ad98c0c..cd5b0d1dc0 100644 --- a/twilio/rest/chat/v2/service/binding.py +++ b/twilio/rest/chat/v2/service/binding.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class BindingInstance(InstanceResource): + class BindingType(object): GCM = "gcm" APN = "apn" @@ -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 @@ -141,6 +179,7 @@ def __repr__(self) -> str: class BindingContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the BindingContext @@ -158,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 @@ -165,9 +218,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -177,9 +252,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance 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) -> BindingInstance: @@ -189,18 +288,45 @@ def fetch(self) -> BindingInstance: :returns: The fetched BindingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return BindingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> BindingInstance: """ @@ -209,18 +335,29 @@ async def fetch_async(self) -> BindingInstance: :returns: The fetched BindingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return BindingInstance( + 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: """ @@ -233,12 +370,14 @@ def __repr__(self) -> str: class BindingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: """ Build an instance of BindingInstance :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -253,6 +392,7 @@ def __repr__(self) -> str: class BindingList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the BindingList @@ -331,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, @@ -354,6 +554,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -386,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( @@ -396,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, @@ -426,8 +690,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return BindingPage(self._version, response, self._solution) + 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 BindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -459,10 +729,96 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return BindingPage(self._version, response, self._solution) + 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: """ @@ -474,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: """ @@ -486,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 82fc71f80b..d2c4bf396c 100644 --- a/twilio/rest/chat/v2/service/channel/__init__.py +++ b/twilio/rest/chat/v2/service/channel/__init__.py @@ -12,10 +12,10 @@ 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 @@ -28,6 +28,7 @@ class ChannelInstance(InstanceResource): + class ChannelType(object): PUBLIC = "public" PRIVATE = "private" @@ -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: """ @@ -268,6 +392,7 @@ def __repr__(self) -> str: class ChannelContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the ChannelContext @@ -290,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[ @@ -303,13 +452,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -324,14 +510,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> ChannelInstance: @@ -341,18 +556,45 @@ def fetch(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ChannelInstance: """ @@ -361,20 +603,31 @@ async def fetch_async(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ChannelInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -385,20 +638,14 @@ 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 + Internal helper for update 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 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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -409,24 +656,26 @@ def update( "CreatedBy": created_by, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return ChannelInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -439,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. @@ -451,26 +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( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - - 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, @@ -478,15 +716,188 @@ 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, - self._solution["service_sid"], + 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"], ) return self._invites @@ -541,12 +952,14 @@ def __repr__(self) -> str: class ChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ Build an instance of ChannelInstance :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -561,6 +974,7 @@ def __repr__(self) -> str: class ChannelList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the ChannelList @@ -577,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 @@ -589,21 +1003,14 @@ 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 - - :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`. + Internal helper for create operation - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -618,17 +1025,60 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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[ + "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 @@ -640,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. @@ -653,8 +1103,43 @@ 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( { "FriendlyName": friendly_name, @@ -669,16 +1154,101 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -733,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, @@ -754,6 +1380,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -783,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( @@ -792,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, @@ -819,8 +1503,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ChannelPage(self._version, response, self._solution) + 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 ChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -849,10 +1539,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ChannelPage(self._version, response, self._solution) + 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: """ @@ -864,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: """ @@ -876,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 3b89e94f85..1a3be5b92a 100644 --- a/twilio/rest/chat/v2/service/channel/invite.py +++ b/twilio/rest/chat/v2/service/channel/invite.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class InviteInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Invite resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Invite resource. @@ -68,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -105,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 @@ -123,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 @@ -134,6 +170,7 @@ def __repr__(self) -> str: class InviteContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the InviteContext @@ -157,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 @@ -164,9 +215,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -176,9 +249,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance 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) -> InviteInstance: @@ -188,19 +285,47 @@ def fetch(self) -> InviteInstance: :returns: The fetched InviteInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return InviteInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> InviteInstance: """ @@ -209,19 +334,31 @@ async def fetch_async(self) -> InviteInstance: :returns: The fetched InviteInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return InviteInstance( + 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: """ @@ -234,12 +371,14 @@ def __repr__(self) -> str: class InvitePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: """ Build an instance of InviteInstance :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -257,6 +396,7 @@ def __repr__(self) -> str: class InviteList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the InviteList @@ -277,30 +417,44 @@ 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( { "Identity": identity, "RoleSid": role_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -308,30 +462,66 @@ 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( { "Identity": identity, "RoleSid": role_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, + 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, @@ -339,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, @@ -393,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, @@ -414,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -443,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( @@ -452,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, @@ -479,8 +805,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return InvitePage(self._version, response, self._solution) + 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 InvitePage(self._version, response, solution=self._solution) async def page_async( self, @@ -509,10 +841,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return InvitePage(self._version, response, self._solution) + 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: """ @@ -524,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: """ @@ -536,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 aa03d8bac3..9e40454a44 100644 --- a/twilio/rest/chat/v2/service/channel/member.py +++ b/twilio/rest/chat/v2/service/channel/member.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class MemberInstance(InstanceResource): + class WebhookEnabledType(object): TRUE = "true" FALSE = "false" @@ -68,9 +69,9 @@ def __init__( self.last_consumed_message_index: Optional[int] = deserialize.integer( payload.get("last_consumed_message_index") ) - self.last_consumption_timestamp: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) self.url: Optional[str] = payload.get("url") self.attributes: Optional[str] = payload.get("attributes") @@ -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 @@ -231,6 +355,7 @@ def __repr__(self) -> str: class MemberContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the MemberContext @@ -254,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[ @@ -267,13 +416,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -288,14 +474,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> MemberInstance: @@ -305,19 +520,47 @@ def fetch(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MemberInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MemberInstance: """ @@ -326,21 +569,33 @@ async def fetch_async(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MemberInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "MemberInstance.WebhookEnabledType", object @@ -351,20 +606,14 @@ 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( { "RoleSid": role_sid, @@ -377,25 +626,26 @@ def update( "Attributes": attributes, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return MemberInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MemberInstance.WebhookEnabledType", object @@ -408,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). @@ -420,28 +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( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - - 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, @@ -450,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 """ @@ -461,12 +876,14 @@ def __repr__(self) -> str: class MemberPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: """ Build an instance of MemberInstance :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -484,6 +901,7 @@ def __repr__(self) -> str: class MemberList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the MemberList @@ -504,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[ @@ -516,21 +934,14 @@ 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( { "Identity": identity, @@ -547,12 +958,55 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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, + 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, @@ -560,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[ @@ -572,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 @@ -585,8 +1039,46 @@ 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( { "Identity": identity, @@ -603,12 +1095,55 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -616,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, @@ -670,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, @@ -691,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -720,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( @@ -729,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, @@ -756,8 +1450,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MemberPage(self._version, response, self._solution) + 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 MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -786,10 +1486,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MemberPage(self._version, response, self._solution) + 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: """ @@ -801,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: """ @@ -813,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 07f6a9dc90..ee6de8ed3d 100644 --- a/twilio/rest/chat/v2/service/channel/message.py +++ b/twilio/rest/chat/v2/service/channel/message.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class MessageInstance(InstanceResource): + class OrderType(object): ASC = "asc" DESC = "desc" @@ -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 @@ -239,6 +363,7 @@ def __repr__(self) -> str: class MessageContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the MessageContext @@ -262,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[ @@ -275,13 +424,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -296,14 +482,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> MessageInstance: @@ -313,19 +528,47 @@ def fetch(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MessageInstance: """ @@ -334,21 +577,33 @@ async def fetch_async(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -359,20 +614,14 @@ 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( { "Body": body, @@ -383,25 +632,26 @@ def update( "From": from_, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return MessageInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -414,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. @@ -426,26 +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( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - - 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, @@ -454,23 +693,201 @@ 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) 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, @@ -488,6 +905,7 @@ def __repr__(self) -> str: class MessageList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the MessageList @@ -508,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 @@ -520,21 +938,14 @@ 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 - - :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. + Internal helper for create operation - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "From": from_, @@ -549,12 +960,55 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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[ + "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, @@ -562,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 @@ -574,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`. @@ -587,8 +1041,46 @@ 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( { "From": from_, @@ -603,12 +1095,55 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -616,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, @@ -670,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, @@ -691,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -720,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( @@ -729,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, @@ -756,8 +1450,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MessagePage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -786,10 +1486,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MessagePage(self._version, response, self._solution) + 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: """ @@ -801,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: """ @@ -813,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 6e05e41742..f5372f3595 100644 --- a/twilio/rest/chat/v2/service/channel/webhook.py +++ b/twilio/rest/chat/v2/service/channel/webhook.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class WebhookInstance(InstanceResource): + class Method(object): GET = "GET" POST = "POST" @@ -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 @@ -200,6 +298,7 @@ def __repr__(self) -> str: class WebhookContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the WebhookContext @@ -223,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 @@ -230,9 +343,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -242,9 +377,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance 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) -> WebhookInstance: @@ -254,19 +413,47 @@ def fetch(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WebhookInstance: """ @@ -275,21 +462,33 @@ async def fetch_async(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + 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( + def _update( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, @@ -297,19 +496,14 @@ 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 - - :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. + Internal helper for update operation - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Configuration.Url": configuration_url, @@ -324,13 +518,45 @@ def update( "Configuration.RetryCount": configuration_retry_count, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -339,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, @@ -347,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: @@ -358,8 +584,41 @@ 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( { "Configuration.Url": configuration_url, @@ -374,48 +633,120 @@ async def update_async( "Configuration.RetryCount": configuration_retry_count, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WebhookInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], - ) + headers["Accept"] = "application/json" - def __repr__(self) -> str: - """ - Provide a friendly representation + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: Machine friendly representation + 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: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - + Asynchronous coroutine to update the WebhookInstance -class WebhookPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: - """ - Build an instance of 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. - :param payload: Payload response from the API + :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, service_sid=self._solution["service_sid"], channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation :returns: Machine friendly representation """ @@ -423,6 +754,7 @@ def __repr__(self) -> str: class WebhookList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the WebhookList @@ -443,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, @@ -452,20 +784,14 @@ 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( { "Type": type, @@ -481,13 +807,48 @@ def create( "Configuration.RetryCount": configuration_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, + 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, @@ -495,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, @@ -504,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`. @@ -516,8 +877,42 @@ 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( { "Type": type, @@ -533,13 +928,48 @@ async def create_async( "Configuration.RetryCount": configuration_retry_count, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -547,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, @@ -597,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, @@ -616,6 +1136,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -642,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( @@ -650,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, @@ -674,8 +1246,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return WebhookPage(self._version, response, self._solution) + 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 WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -701,10 +1279,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return WebhookPage(self._version, response, self._solution) + 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: """ @@ -716,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: """ @@ -728,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 7f77ee6e4b..3c6fff8f9c 100644 --- a/twilio/rest/chat/v2/service/role.py +++ b/twilio/rest/chat/v2/service/role.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class RoleInstance(InstanceResource): + class RoleType(object): CHANNEL = "channel" DEPLOYMENT = "deployment" @@ -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 @@ -156,6 +218,7 @@ def __repr__(self) -> str: class RoleContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the RoleContext @@ -173,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 @@ -180,9 +257,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -192,9 +291,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance 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) -> RoleInstance: @@ -204,18 +327,45 @@ def fetch(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return RoleInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RoleInstance: """ @@ -224,12 +374,7 @@ async def fetch_async(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -237,26 +382,54 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -264,26 +437,55 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -291,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 @@ -302,12 +521,14 @@ def __repr__(self) -> str: class RolePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: """ Build an instance of RoleInstance :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -322,6 +543,7 @@ def __repr__(self) -> str: class RoleList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the RoleList @@ -338,6 +560,33 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: 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.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: @@ -350,6 +599,43 @@ def create( :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"] + ) + + 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, 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( { "FriendlyName": friendly_name, @@ -357,15 +643,14 @@ def create( "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RoleInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -380,23 +665,32 @@ async def create_async( :returns: The created RoleInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Permission": serialize.map(permission, lambda e: e), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return RoleInstance( + 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, @@ -448,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, @@ -467,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -493,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( @@ -501,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, @@ -525,8 +921,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RolePage(self._version, response, self._solution) + 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 RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -552,10 +954,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RolePage(self._version, response, self._solution) + 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: """ @@ -567,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: """ @@ -579,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 9977023e7f..b31d666b71 100644 --- a/twilio/rest/chat/v2/service/user/__init__.py +++ b/twilio/rest/chat/v2/service/user/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,6 +26,7 @@ class UserInstance(InstanceResource): + class WebhookEnabledType(object): TRUE = "true" FALSE = "false" @@ -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: """ @@ -212,6 +302,7 @@ def __repr__(self) -> str: class UserContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the UserContext @@ -232,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 @@ -239,9 +344,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -251,9 +378,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch(self) -> UserInstance: @@ -263,18 +414,45 @@ def fetch(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserInstance: """ @@ -283,20 +461,31 @@ async def fetch_async(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -304,17 +493,14 @@ 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( { "RoleSid": role_sid, @@ -322,16 +508,50 @@ def update( "FriendlyName": friendly_name, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( + 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 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, @@ -339,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 @@ -347,17 +567,47 @@ 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( { "RoleSid": role_sid, @@ -365,16 +615,50 @@ async def update_async( "FriendlyName": friendly_name, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + 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" - payload = await self._version.update_async( + 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[ + "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, @@ -382,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: """ @@ -419,12 +736,14 @@ def __repr__(self) -> str: 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, service_sid=self._solution["service_sid"] ) @@ -439,6 +758,7 @@ def __repr__(self) -> str: class UserList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the UserList @@ -455,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[ @@ -464,18 +784,14 @@ 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 - - :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. + Internal helper for create operation - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Identity": identity, @@ -487,17 +803,51 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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, + 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[ @@ -506,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 @@ -516,8 +866,37 @@ 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( { "Identity": identity, @@ -529,16 +908,83 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -589,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, @@ -608,6 +1104,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -634,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( @@ -642,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, @@ -666,8 +1214,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserPage(self._version, response, self._solution) + 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 UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -693,10 +1247,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserPage(self._version, response, self._solution) + 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: """ @@ -708,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: """ @@ -720,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 5ea1628840..9d9ae604ef 100644 --- a/twilio/rest/chat/v2/service/user/user_binding.py +++ b/twilio/rest/chat/v2/service/user/user_binding.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class UserBindingInstance(InstanceResource): + class BindingType(object): GCM = "gcm" APN = "apn" @@ -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 @@ -144,6 +182,7 @@ def __repr__(self) -> str: class UserBindingContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): """ Initialize the UserBindingContext @@ -165,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 @@ -172,9 +225,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -184,9 +259,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance 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) -> UserBindingInstance: @@ -196,19 +295,47 @@ def fetch(self) -> UserBindingInstance: :returns: The fetched UserBindingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], ) - return UserBindingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserBindingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserBindingInstance: """ @@ -217,19 +344,31 @@ async def fetch_async(self) -> UserBindingInstance: :returns: The fetched UserBindingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], ) - return UserBindingInstance( + 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: """ @@ -242,12 +381,14 @@ def __repr__(self) -> str: class UserBindingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: """ Build an instance of UserBindingInstance :param payload: Payload response from the API """ + return UserBindingInstance( self._version, payload, @@ -265,6 +406,7 @@ def __repr__(self) -> str: class UserBindingList(ListResource): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ Initialize the UserBindingList @@ -345,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[ @@ -368,6 +570,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -399,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( @@ -408,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[ @@ -437,8 +701,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserBindingPage(self._version, response, self._solution) + 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 UserBindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -469,10 +739,94 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserBindingPage(self._version, response, self._solution) + 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: """ @@ -484,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: """ @@ -496,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 2f72e8c59c..1c4fe1c849 100644 --- a/twilio/rest/chat/v2/service/user/user_channel.py +++ b/twilio/rest/chat/v2/service/user/user_channel.py @@ -12,10 +12,10 @@ 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 @@ -24,10 +24,11 @@ class UserChannelInstance(InstanceResource): + class ChannelStatus(object): JOINED = "joined" INVITED = "invited" - NOT_PARTICIPATING = "not_participating" + NOTPARTICIPATING = "notParticipating" class NotificationLevel(object): DEFAULT = "default" @@ -77,15 +78,16 @@ def __init__( ) self.links: Optional[Dict[str, object]] = payload.get("links") self.url: Optional[str] = payload.get("url") - self.notification_level: Optional[ - "UserChannelInstance.NotificationLevel" - ] = payload.get("notification_level") + self.notification_level: Optional["UserChannelInstance.NotificationLevel"] = ( + payload.get("notification_level") + ) self._solution = { "service_sid": service_sid, "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 @@ -214,6 +314,7 @@ def __repr__(self) -> str: class UserChannelContext(InstanceContext): + def __init__( self, version: Version, service_sid: str, user_sid: str, channel_sid: str ): @@ -239,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[ @@ -252,13 +377,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -273,14 +435,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> UserChannelInstance: @@ -290,19 +481,47 @@ def fetch(self) -> UserChannelInstance: :returns: The fetched UserChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], ) - return UserChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserChannelInstance: """ @@ -311,37 +530,47 @@ async def fetch_async(self) -> UserChannelInstance: :returns: The fetched UserChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], ) - return UserChannelInstance( + 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( + 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 - - :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). + Internal helper for update operation - :returns: The updated UserChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "NotificationLevel": notification_level, @@ -351,13 +580,38 @@ def update( ), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -366,23 +620,52 @@ 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( { "NotificationLevel": notification_level, @@ -392,13 +675,38 @@ async def update_async( ), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -407,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 @@ -418,12 +757,14 @@ def __repr__(self) -> str: class UserChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: """ Build an instance of UserChannelInstance :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -441,6 +782,7 @@ def __repr__(self) -> str: class UserChannelList(ListResource): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ Initialize the UserChannelList @@ -511,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, @@ -530,6 +922,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -556,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( @@ -564,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, @@ -588,8 +1032,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserChannelPage(self._version, response, self._solution) + 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 UserChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -615,10 +1065,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserChannelPage(self._version, response, self._solution) + 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: """ @@ -630,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: """ @@ -642,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/__init__.py b/twilio/rest/chat/v3/__init__.py index 7fdfc8977f..582dc44069 100644 --- a/twilio/rest/chat/v3/__init__.py +++ b/twilio/rest/chat/v3/__init__.py @@ -19,6 +19,7 @@ class V3(Version): + def __init__(self, domain: Domain): """ Initialize the V3 version of Chat diff --git a/twilio/rest/chat/v3/channel.py b/twilio/rest/chat/v3/channel.py index 3305bb578c..fa71c46897 100644 --- a/twilio/rest/chat/v3/channel.py +++ b/twilio/rest/chat/v3/channel.py @@ -12,10 +12,10 @@ 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 @@ -23,6 +23,7 @@ class ChannelInstance(InstanceResource): + class ChannelType(object): PUBLIC = "public" PRIVATE = "private" @@ -44,7 +45,7 @@ class WebhookEnabledType(object): :ivar created_by: The `identity` of the User that created the channel. If the Channel was created by using the API, the value is `system`. :ivar members_count: The number of Members in the Channel. :ivar messages_count: The number of Messages that have been passed in the Channel. - :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/sms/services/api) this channel belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this channel belongs to. :ivar url: The absolute URL of the Channel resource. """ @@ -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 @@ -115,7 +117,7 @@ def update( :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/sms/services/api) this channel belongs to. + :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 """ @@ -138,7 +140,7 @@ async def update_async( :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/sms/services/api) this channel belongs to. + :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 """ @@ -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 @@ -159,6 +207,7 @@ def __repr__(self) -> str: class ChannelContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the ChannelContext @@ -176,39 +225,68 @@ 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 - - :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/sms/services/api) this channel belongs to. + Internal helper for update operation - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Type": type, "MessagingServiceSid": messaging_service_sid, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + 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" - payload = self._version.update( + headers["Accept"] = "application/json" + + 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, @@ -216,39 +294,98 @@ 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/sms/services/api) this channel belongs to. + :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( { "Type": type, "MessagingServiceSid": messaging_service_sid, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + 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 - payload = await self._version.update_async( + 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, + 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, @@ -256,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 @@ -267,6 +434,7 @@ def __repr__(self) -> str: class ChannelList(ListResource): + def __init__(self, version: Version): """ Initialize the ChannelList diff --git a/twilio/rest/content/ContentBase.py b/twilio/rest/content/ContentBase.py index 72dfbad76d..8a1ccd5d94 100644 --- a/twilio/rest/content/ContentBase.py +++ b/twilio/rest/content/ContentBase.py @@ -14,9 +14,11 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.content.v1 import V1 +from twilio.rest.content.v2 import V2 class ContentBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Content Domain @@ -25,6 +27,7 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://content.twilio.com") self._v1: Optional[V1] = None + self._v2: Optional[V2] = None @property def v1(self) -> V1: @@ -35,6 +38,15 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Content + """ + 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/content/v1/__init__.py b/twilio/rest/content/v1/__init__.py index 68f3f13a69..1410fe4788 100644 --- a/twilio/rest/content/v1/__init__.py +++ b/twilio/rest/content/v1/__init__.py @@ -21,6 +21,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Content diff --git a/twilio/rest/content/v1/content/__init__.py b/twilio/rest/content/v1/content/__init__.py index b0eaaa0fad..5432e54944 100644 --- a/twilio/rest/content/v1/content/__init__.py +++ b/twilio/rest/content/v1/content/__init__.py @@ -12,20 +12,854 @@ 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 +from twilio.rest.content.v1.content.approval_create import ApprovalCreateList from twilio.rest.content.v1.content.approval_fetch import ApprovalFetchList class ContentInstance(InstanceResource): + class AuthenticationAction(object): + """ + :ivar type: + :ivar copy_code_text: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.AuthenticationActionType"] = ( + payload.get("type") + ) + self.copy_code_text: Optional[str] = payload.get("copy_code_text") + + def to_dict(self): + return { + "type": self.type, + "copy_code_text": self.copy_code_text, + } + + class CallToActionAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar code: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + 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 { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "code": self.code, + "id": self.id, + } + + class CardAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + :ivar code: + :ivar webview_size: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CardActionType"] = payload.get("type") + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + 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 { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + "webview_size": self.webview_size, + } + + class CarouselAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CarouselActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + } + + class CarouselCard(object): + """ + :ivar title: + :ivar body: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.media: Optional[str] = payload.get("media") + self.actions: Optional[List[ContentList.CarouselAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class CatalogItem(object): + """ + :ivar id: + :ivar section_title: + :ivar name: + :ivar media_url: + :ivar price: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.section_title: Optional[str] = payload.get("section_title") + self.name: Optional[str] = payload.get("name") + self.media_url: Optional[str] = payload.get("media_url") + self.price: Optional[float] = payload.get("price") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "section_title": self.section_title, + "name": self.name, + "media_url": self.media_url, + "price": self.price, + "description": self.description, + } + + class ContentCreateRequest(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") + + 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") + + 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 FlowsPage(object): + """ + :ivar id: + :ivar next_page_id: + :ivar title: + :ivar subtitle: + :ivar layout: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.next_page_id: Optional[str] = payload.get("next_page_id") + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.layout: Optional[List[ContentList.FlowsPageComponent]] = payload.get( + "layout" + ) + + def to_dict(self): + return { + "id": self.id, + "next_page_id": self.next_page_id, + "title": self.title, + "subtitle": self.subtitle, + "layout": ( + [layout.to_dict() for layout in self.layout] + if self.layout is not None + else None + ), + } + + class FlowsPageComponent(object): + """ + :ivar label: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "label": self.label, + "type": self.type, + } + + class ListItem(object): + """ + :ivar id: + :ivar item: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.item: Optional[str] = payload.get("item") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "item": self.item, + "description": self.description, + } + + class QuickReplyAction(object): + """ + :ivar type: + :ivar title: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "id": self.id, + } + + class TwilioCallToAction(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCard(object): + """ + :ivar title: + :ivar subtitle: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media: Optional[List[str]] = payload.get("media") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "subtitle": self.subtitle, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCarousel(object): + """ + :ivar body: + :ivar cards: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.cards: Optional[List[ContentList.CarouselCard]] = payload.get("cards") + + def to_dict(self): + return { + "body": self.body, + "cards": ( + [cards.to_dict() for cards in self.cards] + if self.cards is not None + else None + ), + } + + class TwilioCatalog(object): + """ + :ivar title: + :ivar body: + :ivar subtitle: + :ivar id: + :ivar items: + :ivar dynamic_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.subtitle: Optional[str] = payload.get("subtitle") + self.id: Optional[str] = payload.get("id") + self.items: Optional[List[ContentList.CatalogItem]] = payload.get("items") + self.dynamic_items: Optional[str] = payload.get("dynamic_items") + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "subtitle": self.subtitle, + "id": self.id, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + "dynamic_items": self.dynamic_items, + } + + class TwilioFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar pages: + :ivar type: + """ + + 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.pages: Optional[List[ContentList.FlowsPage]] = payload.get("pages") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "pages": ( + [pages.to_dict() for pages in self.pages] + if self.pages is not None + else None + ), + "type": self.type, + } + + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") + + def to_dict(self): + return { + "body": self.body, + "button": self.button, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + } + + class TwilioLocation(object): + """ + :ivar latitude: + :ivar longitude: + :ivar label: + :ivar id: + :ivar address: + """ + + 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): + """ + :ivar body: + :ivar media: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[str]] = payload.get("media") + + def to_dict(self): + return { + "body": self.body, + "media": self.media, + } + + class TwilioQuickReply(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + 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: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + + def to_dict(self): + return { + "body": self.body, + } + + class Types(object): + """ + :ivar twilio_text: + :ivar twilio_media: + :ivar twilio_location: + :ivar twilio_list_picker: + :ivar twilio_call_to_action: + :ivar twilio_quick_reply: + :ivar twilio_card: + :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" + ) + self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( + "twilio/media" + ) + self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( + "twilio/location" + ) + self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( + payload.get("twilio/list-picker") + ) + self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( + payload.get("twilio/call-to-action") + ) + self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( + payload.get("twilio/quick-reply") + ) + self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( + "twilio/card" + ) + self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( + "twilio/catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio/carousel" + ) + self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( + "twilio/flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio/schedule" + ) + self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( + "whatsapp/card" + ) + self.whatsapp_authentication: Optional[ + ContentList.WhatsappAuthentication + ] = payload.get("whatsapp/authentication") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) + + def to_dict(self): + return { + "twilio/text": ( + self.twilio_text.to_dict() if self.twilio_text is not None else None + ), + "twilio/media": ( + self.twilio_media.to_dict() + if self.twilio_media is not None + else None + ), + "twilio/location": ( + self.twilio_location.to_dict() + if self.twilio_location is not None + else None + ), + "twilio/list-picker": ( + self.twilio_list_picker.to_dict() + if self.twilio_list_picker is not None + else None + ), + "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": ( + self.twilio_quick_reply.to_dict() + if self.twilio_quick_reply is not None + else None + ), + "twilio/card": ( + self.twilio_card.to_dict() if self.twilio_card is not None else None + ), + "twilio/catalog": ( + self.twilio_catalog.to_dict() + if self.twilio_catalog is not None + else None + ), + "twilio/carousel": ( + self.twilio_carousel.to_dict() + if self.twilio_carousel is not None + else None + ), + "twilio/flows": ( + self.twilio_flows.to_dict() + if self.twilio_flows is not None + else None + ), + "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": ( + 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): + """ + :ivar add_security_recommendation: + :ivar code_expiration_minutes: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.add_security_recommendation: Optional[bool] = payload.get( + "add_security_recommendation" + ) + self.code_expiration_minutes: Optional[float] = payload.get( + "code_expiration_minutes" + ) + self.actions: Optional[List[ContentList.AuthenticationAction]] = ( + payload.get("actions") + ) + + def to_dict(self): + return { + "add_security_recommendation": self.add_security_recommendation, + "code_expiration_minutes": self.code_expiration_minutes, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class WhatsappCard(object): + """ + :ivar body: + :ivar footer: + :ivar media: + :ivar header_text: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.footer: Optional[str] = payload.get("footer") + self.media: Optional[List[str]] = payload.get("media") + self.header_text: Optional[str] = payload.get("header_text") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "footer": self.footer, + "media": self.media, + "header_text": self.header_text, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + 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" + + class CallToActionActionType(object): + URL = "URL" + PHONE_NUMBER = "PHONE_NUMBER" + COPY_CODE = "COPY_CODE" + VOICE_CALL = "VOICE_CALL" + VOICE_CALL_REQUEST = "VOICE_CALL_REQUEST" + + class CardActionType(object): + URL = "URL" + PHONE_NUMBER = "PHONE_NUMBER" + QUICK_REPLY = "QUICK_REPLY" + COPY_CODE = "COPY_CODE" + VOICE_CALL = "VOICE_CALL" + + class CarouselActionType(object): + URL = "URL" + PHONE_NUMBER = "PHONE_NUMBER" + QUICK_REPLY = "QUICK_REPLY" + + 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. @@ -62,6 +896,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ContentContext] = None @property @@ -84,185 +919,2195 @@ def delete(self) -> bool: Deletes the ContentInstance - :returns: True if delete succeeds, False otherwise + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ContentInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched ContentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ContentInstance": + """ + Asynchronous coroutine to fetch the ContentInstance + + + :returns: The fetched 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: + """ + Access the approval_create + """ + return self._proxy.approval_create + + @property + def approval_fetch(self) -> ApprovalFetchList: + """ + Access the approval_fetch + """ + return self._proxy.approval_fetch + + 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 ContentContext(InstanceContext): + + class AuthenticationAction(object): + """ + :ivar type: + :ivar copy_code_text: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.AuthenticationActionType"] = ( + payload.get("type") + ) + self.copy_code_text: Optional[str] = payload.get("copy_code_text") + + def to_dict(self): + return { + "type": self.type, + "copy_code_text": self.copy_code_text, + } + + class CallToActionAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar code: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + 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 { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "code": self.code, + "id": self.id, + } + + class CardAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + :ivar code: + :ivar webview_size: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CardActionType"] = payload.get("type") + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + 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 { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + "webview_size": self.webview_size, + } + + class CarouselAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CarouselActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + } + + class CarouselCard(object): + """ + :ivar title: + :ivar body: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.media: Optional[str] = payload.get("media") + self.actions: Optional[List[ContentList.CarouselAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class CatalogItem(object): + """ + :ivar id: + :ivar section_title: + :ivar name: + :ivar media_url: + :ivar price: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.section_title: Optional[str] = payload.get("section_title") + self.name: Optional[str] = payload.get("name") + self.media_url: Optional[str] = payload.get("media_url") + self.price: Optional[float] = payload.get("price") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "section_title": self.section_title, + "name": self.name, + "media_url": self.media_url, + "price": self.price, + "description": self.description, + } + + class ContentCreateRequest(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") + + 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") + + 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 FlowsPage(object): + """ + :ivar id: + :ivar next_page_id: + :ivar title: + :ivar subtitle: + :ivar layout: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.next_page_id: Optional[str] = payload.get("next_page_id") + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.layout: Optional[List[ContentList.FlowsPageComponent]] = payload.get( + "layout" + ) + + def to_dict(self): + return { + "id": self.id, + "next_page_id": self.next_page_id, + "title": self.title, + "subtitle": self.subtitle, + "layout": ( + [layout.to_dict() for layout in self.layout] + if self.layout is not None + else None + ), + } + + class FlowsPageComponent(object): + """ + :ivar label: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "label": self.label, + "type": self.type, + } + + class ListItem(object): + """ + :ivar id: + :ivar item: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.item: Optional[str] = payload.get("item") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "item": self.item, + "description": self.description, + } + + class QuickReplyAction(object): + """ + :ivar type: + :ivar title: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "id": self.id, + } + + class TwilioCallToAction(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCard(object): + """ + :ivar title: + :ivar subtitle: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media: Optional[List[str]] = payload.get("media") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "subtitle": self.subtitle, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCarousel(object): + """ + :ivar body: + :ivar cards: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.cards: Optional[List[ContentList.CarouselCard]] = payload.get("cards") + + def to_dict(self): + return { + "body": self.body, + "cards": ( + [cards.to_dict() for cards in self.cards] + if self.cards is not None + else None + ), + } + + class TwilioCatalog(object): + """ + :ivar title: + :ivar body: + :ivar subtitle: + :ivar id: + :ivar items: + :ivar dynamic_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.subtitle: Optional[str] = payload.get("subtitle") + self.id: Optional[str] = payload.get("id") + self.items: Optional[List[ContentList.CatalogItem]] = payload.get("items") + self.dynamic_items: Optional[str] = payload.get("dynamic_items") + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "subtitle": self.subtitle, + "id": self.id, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + "dynamic_items": self.dynamic_items, + } + + class TwilioFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar pages: + :ivar type: + """ + + 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.pages: Optional[List[ContentList.FlowsPage]] = payload.get("pages") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "pages": ( + [pages.to_dict() for pages in self.pages] + if self.pages is not None + else None + ), + "type": self.type, + } + + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") + + def to_dict(self): + return { + "body": self.body, + "button": self.button, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + } + + class TwilioLocation(object): + """ + :ivar latitude: + :ivar longitude: + :ivar label: + :ivar id: + :ivar address: + """ + + 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): + """ + :ivar body: + :ivar media: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[str]] = payload.get("media") + + def to_dict(self): + return { + "body": self.body, + "media": self.media, + } + + class TwilioQuickReply(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + 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: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + + def to_dict(self): + return { + "body": self.body, + } + + class Types(object): + """ + :ivar twilio_text: + :ivar twilio_media: + :ivar twilio_location: + :ivar twilio_list_picker: + :ivar twilio_call_to_action: + :ivar twilio_quick_reply: + :ivar twilio_card: + :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" + ) + self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( + "twilio/media" + ) + self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( + "twilio/location" + ) + self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( + payload.get("twilio/list-picker") + ) + self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( + payload.get("twilio/call-to-action") + ) + self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( + payload.get("twilio/quick-reply") + ) + self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( + "twilio/card" + ) + self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( + "twilio/catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio/carousel" + ) + self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( + "twilio/flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio/schedule" + ) + self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( + "whatsapp/card" + ) + self.whatsapp_authentication: Optional[ + ContentList.WhatsappAuthentication + ] = payload.get("whatsapp/authentication") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) + + def to_dict(self): + return { + "twilio/text": ( + self.twilio_text.to_dict() if self.twilio_text is not None else None + ), + "twilio/media": ( + self.twilio_media.to_dict() + if self.twilio_media is not None + else None + ), + "twilio/location": ( + self.twilio_location.to_dict() + if self.twilio_location is not None + else None + ), + "twilio/list-picker": ( + self.twilio_list_picker.to_dict() + if self.twilio_list_picker is not None + else None + ), + "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": ( + self.twilio_quick_reply.to_dict() + if self.twilio_quick_reply is not None + else None + ), + "twilio/card": ( + self.twilio_card.to_dict() if self.twilio_card is not None else None + ), + "twilio/catalog": ( + self.twilio_catalog.to_dict() + if self.twilio_catalog is not None + else None + ), + "twilio/carousel": ( + self.twilio_carousel.to_dict() + if self.twilio_carousel is not None + else None + ), + "twilio/flows": ( + self.twilio_flows.to_dict() + if self.twilio_flows is not None + else None + ), + "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": ( + 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): + """ + :ivar add_security_recommendation: + :ivar code_expiration_minutes: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.add_security_recommendation: Optional[bool] = payload.get( + "add_security_recommendation" + ) + self.code_expiration_minutes: Optional[float] = payload.get( + "code_expiration_minutes" + ) + self.actions: Optional[List[ContentList.AuthenticationAction]] = ( + payload.get("actions") + ) + + def to_dict(self): + return { + "add_security_recommendation": self.add_security_recommendation, + "code_expiration_minutes": self.code_expiration_minutes, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class WhatsappCard(object): + """ + :ivar body: + :ivar footer: + :ivar media: + :ivar header_text: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.footer: Optional[str] = payload.get("footer") + self.media: Optional[List[str]] = payload.get("media") + self.header_text: Optional[str] = payload.get("header_text") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "footer": self.footer, + "media": self.media, + "header_text": self.header_text, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + 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 update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Content/{sid}".format(**self._solution) + + 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 + + + :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 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 ContentInstance + + + :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 ContentInstance 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) -> ContentInstance: + """ + Fetch the ContentInstance + + + :returns: The fetched ContentInstance + """ + payload, _, _ = self._fetch() + return ContentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ContentInstance and return response metadata + + + :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" + + 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"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ContentInstance and return response metadata + + + :returns: ApiResponse with instance, status code, and headers + """ + 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 + + @property + def approval_fetch(self) -> ApprovalFetchList: + """ + Access the approval_fetch + """ + if self._approval_fetch is None: + self._approval_fetch = ApprovalFetchList( + self._version, + self._solution["sid"], + ) + return self._approval_fetch + + 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 ContentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: + """ + Build an instance of ContentInstance + + :param payload: Payload response from the API + """ + + return ContentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ContentList(ListResource): + + class AuthenticationAction(object): + """ + :ivar type: + :ivar copy_code_text: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.AuthenticationActionType"] = ( + payload.get("type") + ) + self.copy_code_text: Optional[str] = payload.get("copy_code_text") + + def to_dict(self): + return { + "type": self.type, + "copy_code_text": self.copy_code_text, + } + + class CallToActionAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar code: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CallToActionActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + 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 { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "code": self.code, + "id": self.id, + } + + class CardAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + :ivar code: + :ivar webview_size: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CardActionType"] = payload.get("type") + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + 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 { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + "code": self.code, + "webview_size": self.webview_size, + } + + class CarouselAction(object): + """ + :ivar type: + :ivar title: + :ivar url: + :ivar phone: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.CarouselActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.url: Optional[str] = payload.get("url") + self.phone: Optional[str] = payload.get("phone") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "url": self.url, + "phone": self.phone, + "id": self.id, + } + + class CarouselCard(object): + """ + :ivar title: + :ivar body: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.media: Optional[str] = payload.get("media") + self.actions: Optional[List[ContentList.CarouselAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class CatalogItem(object): + """ + :ivar id: + :ivar section_title: + :ivar name: + :ivar media_url: + :ivar price: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.section_title: Optional[str] = payload.get("section_title") + self.name: Optional[str] = payload.get("name") + self.media_url: Optional[str] = payload.get("media_url") + self.price: Optional[float] = payload.get("price") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "section_title": self.section_title, + "name": self.name, + "media_url": self.media_url, + "price": self.price, + "description": self.description, + } + + class ContentCreateRequest(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") + + 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") + + 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 FlowsPage(object): + """ + :ivar id: + :ivar next_page_id: + :ivar title: + :ivar subtitle: + :ivar layout: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.next_page_id: Optional[str] = payload.get("next_page_id") + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.layout: Optional[List[ContentList.FlowsPageComponent]] = payload.get( + "layout" + ) + + def to_dict(self): + return { + "id": self.id, + "next_page_id": self.next_page_id, + "title": self.title, + "subtitle": self.subtitle, + "layout": ( + [layout.to_dict() for layout in self.layout] + if self.layout is not None + else None + ), + } + + class FlowsPageComponent(object): + """ + :ivar label: + :ivar type: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.label: Optional[str] = payload.get("label") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "label": self.label, + "type": self.type, + } + + class ListItem(object): + """ + :ivar id: + :ivar item: + :ivar description: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + self.item: Optional[str] = payload.get("item") + self.description: Optional[str] = payload.get("description") + + def to_dict(self): + return { + "id": self.id, + "item": self.item, + "description": self.description, + } + + class QuickReplyAction(object): + """ + :ivar type: + :ivar title: + :ivar id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["ContentInstance.QuickReplyActionType"] = payload.get( + "type" + ) + self.title: Optional[str] = payload.get("title") + self.id: Optional[str] = payload.get("id") + + def to_dict(self): + return { + "type": self.type, + "title": self.title, + "id": self.id, + } + + class TwilioCallToAction(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.CallToActionAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCard(object): + """ + :ivar title: + :ivar subtitle: + :ivar media: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.subtitle: Optional[str] = payload.get("subtitle") + self.media: Optional[List[str]] = payload.get("media") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "title": self.title, + "subtitle": self.subtitle, + "media": self.media, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + class TwilioCarousel(object): + """ + :ivar body: + :ivar cards: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.cards: Optional[List[ContentList.CarouselCard]] = payload.get("cards") + + def to_dict(self): + return { + "body": self.body, + "cards": ( + [cards.to_dict() for cards in self.cards] + if self.cards is not None + else None + ), + } + + class TwilioCatalog(object): + """ + :ivar title: + :ivar body: + :ivar subtitle: + :ivar id: + :ivar items: + :ivar dynamic_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.title: Optional[str] = payload.get("title") + self.body: Optional[str] = payload.get("body") + self.subtitle: Optional[str] = payload.get("subtitle") + self.id: Optional[str] = payload.get("id") + self.items: Optional[List[ContentList.CatalogItem]] = payload.get("items") + self.dynamic_items: Optional[str] = payload.get("dynamic_items") + + def to_dict(self): + return { + "title": self.title, + "body": self.body, + "subtitle": self.subtitle, + "id": self.id, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + "dynamic_items": self.dynamic_items, + } + + class TwilioFlows(object): + """ + :ivar body: + :ivar button_text: + :ivar subtitle: + :ivar media_url: + :ivar pages: + :ivar type: + """ + + 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.pages: Optional[List[ContentList.FlowsPage]] = payload.get("pages") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "body": self.body, + "button_text": self.button_text, + "subtitle": self.subtitle, + "media_url": self.media_url, + "pages": ( + [pages.to_dict() for pages in self.pages] + if self.pages is not None + else None + ), + "type": self.type, + } + + class TwilioListPicker(object): + """ + :ivar body: + :ivar button: + :ivar items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.button: Optional[str] = payload.get("button") + self.items: Optional[List[ContentList.ListItem]] = payload.get("items") + + def to_dict(self): + return { + "body": self.body, + "button": self.button, + "items": ( + [items.to_dict() for items in self.items] + if self.items is not None + else None + ), + } + + class TwilioLocation(object): + """ + :ivar latitude: + :ivar longitude: + :ivar label: + :ivar id: + :ivar address: + """ + + 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): + """ + :ivar body: + :ivar media: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.media: Optional[List[str]] = payload.get("media") + + def to_dict(self): + return { + "body": self.body, + "media": self.media, + } + + class TwilioQuickReply(object): + """ + :ivar body: + :ivar actions: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + self.actions: Optional[List[ContentList.QuickReplyAction]] = payload.get( + "actions" + ) + + def to_dict(self): + return { + "body": self.body, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } + + 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: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.body: Optional[str] = payload.get("body") + + def to_dict(self): + return { + "body": self.body, + } + + class Types(object): + """ + :ivar twilio_text: + :ivar twilio_media: + :ivar twilio_location: + :ivar twilio_list_picker: + :ivar twilio_call_to_action: + :ivar twilio_quick_reply: + :ivar twilio_card: + :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" + ) + self.twilio_media: Optional[ContentList.TwilioMedia] = payload.get( + "twilio/media" + ) + self.twilio_location: Optional[ContentList.TwilioLocation] = payload.get( + "twilio/location" + ) + self.twilio_list_picker: Optional[ContentList.TwilioListPicker] = ( + payload.get("twilio/list-picker") + ) + self.twilio_call_to_action: Optional[ContentList.TwilioCallToAction] = ( + payload.get("twilio/call-to-action") + ) + self.twilio_quick_reply: Optional[ContentList.TwilioQuickReply] = ( + payload.get("twilio/quick-reply") + ) + self.twilio_card: Optional[ContentList.TwilioCard] = payload.get( + "twilio/card" + ) + self.twilio_catalog: Optional[ContentList.TwilioCatalog] = payload.get( + "twilio/catalog" + ) + self.twilio_carousel: Optional[ContentList.TwilioCarousel] = payload.get( + "twilio/carousel" + ) + self.twilio_flows: Optional[ContentList.TwilioFlows] = payload.get( + "twilio/flows" + ) + self.twilio_schedule: Optional[ContentList.TwilioSchedule] = payload.get( + "twilio/schedule" + ) + self.whatsapp_card: Optional[ContentList.WhatsappCard] = payload.get( + "whatsapp/card" + ) + self.whatsapp_authentication: Optional[ + ContentList.WhatsappAuthentication + ] = payload.get("whatsapp/authentication") + self.whatsapp_flows: Optional[ContentList.WhatsappFlows] = payload.get( + "whatsapp/flows" + ) + + def to_dict(self): + return { + "twilio/text": ( + self.twilio_text.to_dict() if self.twilio_text is not None else None + ), + "twilio/media": ( + self.twilio_media.to_dict() + if self.twilio_media is not None + else None + ), + "twilio/location": ( + self.twilio_location.to_dict() + if self.twilio_location is not None + else None + ), + "twilio/list-picker": ( + self.twilio_list_picker.to_dict() + if self.twilio_list_picker is not None + else None + ), + "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": ( + self.twilio_quick_reply.to_dict() + if self.twilio_quick_reply is not None + else None + ), + "twilio/card": ( + self.twilio_card.to_dict() if self.twilio_card is not None else None + ), + "twilio/catalog": ( + self.twilio_catalog.to_dict() + if self.twilio_catalog is not None + else None + ), + "twilio/carousel": ( + self.twilio_carousel.to_dict() + if self.twilio_carousel is not None + else None + ), + "twilio/flows": ( + self.twilio_flows.to_dict() + if self.twilio_flows is not None + else None + ), + "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": ( + 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): """ - return self._proxy.delete() - - async def delete_async(self) -> bool: + :ivar add_security_recommendation: + :ivar code_expiration_minutes: + :ivar actions: """ - Asynchronous coroutine that deletes the ContentInstance + def __init__(self, payload: Dict[str, Any]): - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "ContentInstance": - """ - Fetch the ContentInstance + self.add_security_recommendation: Optional[bool] = payload.get( + "add_security_recommendation" + ) + self.code_expiration_minutes: Optional[float] = payload.get( + "code_expiration_minutes" + ) + self.actions: Optional[List[ContentList.AuthenticationAction]] = ( + payload.get("actions") + ) + def to_dict(self): + return { + "add_security_recommendation": self.add_security_recommendation, + "code_expiration_minutes": self.code_expiration_minutes, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } - :returns: The fetched ContentInstance + class WhatsappCard(object): """ - return self._proxy.fetch() - - async def fetch_async(self) -> "ContentInstance": + :ivar body: + :ivar footer: + :ivar media: + :ivar header_text: + :ivar actions: """ - Asynchronous coroutine to fetch the ContentInstance + def __init__(self, payload: Dict[str, Any]): - :returns: The fetched ContentInstance - """ - return await self._proxy.fetch_async() + self.body: Optional[str] = payload.get("body") + self.footer: Optional[str] = payload.get("footer") + self.media: Optional[List[str]] = payload.get("media") + self.header_text: Optional[str] = payload.get("header_text") + self.actions: Optional[List[ContentList.CardAction]] = payload.get( + "actions" + ) - @property - def approval_fetch(self) -> ApprovalFetchList: - """ - Access the approval_fetch - """ - return self._proxy.approval_fetch + def to_dict(self): + return { + "body": self.body, + "footer": self.footer, + "media": self.media, + "header_text": self.header_text, + "actions": ( + [actions.to_dict() for actions in self.actions] + if self.actions is not None + else None + ), + } - def __repr__(self) -> str: + class WhatsappFlows(object): """ - Provide a friendly representation - - :returns: Machine friendly representation + :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: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + 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 ContentContext(InstanceContext): - def __init__(self, version: Version, sid: str): + def __init__(self, version: Version): """ - Initialize the ContentContext + Initialize the ContentList :param version: Version that contains the resource - :param sid: The Twilio-provided string that uniquely identifies the Content resource to fetch. + """ super().__init__(version) - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Content/{sid}".format(**self._solution) - - self._approval_fetch: Optional[ApprovalFetchList] = None + self._uri = "/Content" - def delete(self) -> bool: + def _create(self, content_create_request: ContentCreateRequest) -> tuple: """ - Deletes the ContentInstance + Internal helper for create operation - - :returns: True if delete succeeds, False otherwise + Returns: + tuple: (payload, status_code, headers) """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) + data = content_create_request.to_dict() - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ContentInstance + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/json" - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + headers["Accept"] = "application/json" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - def fetch(self) -> ContentInstance: + def create(self, content_create_request: ContentCreateRequest) -> ContentInstance: """ - Fetch the ContentInstance + Create the ContentInstance + :param content_create_request: - :returns: The fetched ContentInstance + :returns: The created ContentInstance """ + payload, _, _ = self._create(content_create_request=content_create_request) + return ContentInstance(self._version, payload) - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return ContentInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ContentInstance: + def create_with_http_info( + self, content_create_request: ContentCreateRequest + ) -> ApiResponse: """ - Asynchronous coroutine to fetch the ContentInstance + Create the ContentInstance and return response metadata + :param content_create_request: - :returns: The fetched ContentInstance + :returns: ApiResponse with instance, status code, and headers """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return ContentInstance( - self._version, - payload, - sid=self._solution["sid"], + 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) - @property - def approval_fetch(self) -> ApprovalFetchList: - """ - Access the approval_fetch + async def _create_async( + self, content_create_request: ContentCreateRequest + ) -> tuple: """ - if self._approval_fetch is None: - self._approval_fetch = ApprovalFetchList( - self._version, - self._solution["sid"], - ) - return self._approval_fetch + Internal async helper for create operation - def __repr__(self) -> str: + Returns: + tuple: (payload, status_code, headers) """ - Provide a friendly representation + data = content_create_request.to_dict() - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + headers["Content-Type"] = "application/json" -class ContentPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: - """ - Build an instance of ContentInstance + headers["Accept"] = "application/json" - :param payload: Payload response from the API - """ - return ContentInstance(self._version, payload) + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - def __repr__(self) -> str: + async def create_async( + self, content_create_request: ContentCreateRequest + ) -> ContentInstance: """ - Provide a friendly representation + Asynchronously create the ContentInstance - :returns: Machine friendly representation - """ - return "" + :param content_create_request: + :returns: The created ContentInstance + """ + payload, _, _ = await self._create_async( + content_create_request=content_create_request + ) + return ContentInstance(self._version, payload) -class ContentList(ListResource): - def __init__(self, version: Version): + async def create_with_http_info_async( + self, content_create_request: ContentCreateRequest + ) -> ApiResponse: """ - Initialize the ContentList + Asynchronously create the ContentInstance and return response metadata - :param version: Version that contains the resource + :param content_create_request: + :returns: ApiResponse with instance, status code, and headers """ - super().__init__(version) - - self._uri = "/Content" + 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, @@ -314,6 +3159,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, @@ -333,6 +3228,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -359,6 +3255,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -367,6 +3264,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, @@ -391,7 +3338,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 ContentPage(self._version, response) async def page_async( @@ -418,11 +3371,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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. @@ -451,7 +3478,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) @@ -459,7 +3486,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 new file mode 100644 index 0000000000..2487ec6090 --- /dev/null +++ b/twilio/rest/content/v1/content/approval_create.py @@ -0,0 +1,229 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + 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 ApprovalCreateInstance(InstanceResource): + + class ContentApprovalRequest(object): + """ + :ivar name: Name of the template. + :ivar category: A WhatsApp recognized template category. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.category: Optional[str] = payload.get("category") + + def to_dict(self): + return { + "name": self.name, + "category": self.category, + } + + """ + :ivar name: + :ivar category: + :ivar content_type: + :ivar status: + :ivar rejection_reason: + :ivar allow_category_change: + """ + + def __init__(self, version: Version, payload: Dict[str, Any], content_sid: str): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.category: Optional[str] = payload.get("category") + self.content_type: Optional[str] = payload.get("content_type") + self.status: Optional[str] = payload.get("status") + self.rejection_reason: Optional[str] = payload.get("rejection_reason") + self.allow_category_change: Optional[bool] = payload.get( + "allow_category_change" + ) + + self._solution = { + "content_sid": content_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 ApprovalCreateList(ListResource): + + class ContentApprovalRequest(object): + """ + :ivar name: Name of the template. + :ivar category: A WhatsApp recognized template category. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.name: Optional[str] = payload.get("name") + self.category: Optional[str] = payload.get("category") + + def to_dict(self): + return { + "name": self.name, + "category": self.category, + } + + def __init__(self, version: Version, content_sid: str): + """ + Initialize the ApprovalCreateList + + :param version: Version that contains the resource + :param content_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "content_sid": content_sid, + } + self._uri = "/Content/{content_sid}/ApprovalRequests/whatsapp".format( + **self._solution + ) + + def _create(self, content_approval_request: ContentApprovalRequest) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = content_approval_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, 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"] + ) + + def create_with_http_info( + self, content_approval_request: ContentApprovalRequest + ) -> ApiResponse: + """ + Create the ApprovalCreateInstance and return response metadata + + :param content_approval_request: + + :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() + + 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, 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/content/v1/content/approval_fetch.py b/twilio/rest/content/v1/content/approval_fetch.py index ccd3b96d84..47b00a89ec 100644 --- a/twilio/rest/content/v1/content/approval_fetch.py +++ b/twilio/rest/content/v1/content/approval_fetch.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class ApprovalFetchInstance(InstanceResource): - """ :ivar sid: The unique string that that we created to identify the Content resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. @@ -40,6 +40,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], sid: str): self._solution = { "sid": sid, } + self._context: Optional[ApprovalFetchContext] = None @property @@ -75,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 @@ -86,6 +105,7 @@ def __repr__(self) -> str: class ApprovalFetchContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ApprovalFetchContext @@ -101,6 +121,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Content/{sid}/ApprovalRequests".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) -> ApprovalFetchInstance: """ Fetch the ApprovalFetchInstance @@ -108,17 +144,43 @@ def fetch(self) -> ApprovalFetchInstance: :returns: The fetched ApprovalFetchInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ApprovalFetchInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApprovalFetchInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ApprovalFetchInstance: """ @@ -127,17 +189,27 @@ async def fetch_async(self) -> ApprovalFetchInstance: :returns: The fetched ApprovalFetchInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ApprovalFetchInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ApprovalFetchInstance( + 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: """ @@ -150,6 +222,7 @@ def __repr__(self) -> str: class ApprovalFetchList(ListResource): + def __init__(self, version: Version, sid: str): """ Initialize the ApprovalFetchList diff --git a/twilio/rest/content/v1/content_and_approvals.py b/twilio/rest/content/v1/content_and_approvals.py index 914376ea0b..73c009e1be 100644 --- a/twilio/rest/content/v1/content_and_approvals.py +++ b/twilio/rest/content/v1/content_and_approvals.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,7 +24,6 @@ class ContentAndApprovalsInstance(InstanceResource): - """ :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. @@ -67,12 +66,14 @@ def __repr__(self) -> str: class ContentAndApprovalsPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: """ Build an instance of ContentAndApprovalsInstance :param payload: Payload response from the API """ + return ContentAndApprovalsInstance(self._version, payload) def __repr__(self) -> str: @@ -85,6 +86,7 @@ def __repr__(self) -> str: class ContentAndApprovalsList(ListResource): + def __init__(self, version: Version): """ Initialize the ContentAndApprovalsList @@ -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, @@ -223,7 +327,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 ContentAndApprovalsPage(self._version, response) async def page_async( @@ -250,11 +360,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 9a1370b98a..a600809360 100644 --- a/twilio/rest/content/v1/legacy_content.py +++ b/twilio/rest/content/v1/legacy_content.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,7 +24,6 @@ class LegacyContentInstance(InstanceResource): - """ :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. @@ -69,12 +68,14 @@ def __repr__(self) -> str: class LegacyContentPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> LegacyContentInstance: """ Build an instance of LegacyContentInstance :param payload: Payload response from the API """ + return LegacyContentInstance(self._version, payload) def __repr__(self) -> str: @@ -87,6 +88,7 @@ def __repr__(self) -> str: class LegacyContentList(ListResource): + def __init__(self, version: Version): """ Initialize the LegacyContentList @@ -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, @@ -225,7 +329,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 LegacyContentPage(self._version, response) async def page_async( @@ -252,11 +362,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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/__init__.py b/twilio/rest/content/v2/__init__.py new file mode 100644 index 0000000000..ca6d8bcd74 --- /dev/null +++ b/twilio/rest/content/v2/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + 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.content.v2.content import ContentList +from twilio.rest.content.v2.content_and_approvals import ContentAndApprovalsList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Content + + :param domain: The Twilio.content domain + """ + super().__init__(domain, "v2") + self._contents: Optional[ContentList] = None + self._content_and_approvals: Optional[ContentAndApprovalsList] = None + + @property + def contents(self) -> ContentList: + if self._contents is None: + self._contents = ContentList(self) + return self._contents + + @property + def content_and_approvals(self) -> ContentAndApprovalsList: + if self._content_and_approvals is None: + self._content_and_approvals = ContentAndApprovalsList(self) + return self._content_and_approvals + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/content/v2/content.py b/twilio/rest/content/v2/content.py new file mode 100644 index 0000000000..2584c2fd5d --- /dev/null +++ b/twilio/rest/content/v2/content.py @@ -0,0 +1,802 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + 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_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ContentInstance(InstanceResource): + """ + :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 sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar url: The URL of the resource, relative to `https://content.twilio.com`. + :ivar links: A list of links related to the Content resource, such as approval_fetch and approval_create + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + 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.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.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.url: Optional[str] = payload.get("url") + self.links: Optional[Dict[str, object]] = payload.get("links") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ContentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentInstance: + """ + Build an instance of ContentInstance + + :param payload: Payload response from the API + """ + + return ContentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ContentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ContentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Content" + + def stream( + 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, + ) -> Iterator[ContentInstance]: + """ + Streams ContentInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + 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"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_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, + ) -> AsyncIterator[ContentInstance]: + """ + Asynchronously streams ContentInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_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"], + ) + + 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, + 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, + ) -> List[ContentInstance]: + """ + Lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + 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, + ) + ) + + async def list_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, + ) -> List[ContentInstance]: + """ + Asynchronously lists ContentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_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, + ) + ] + + 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, + 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, + ) -> ContentPage: + """ + Retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :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: Page of ContentInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentPage(self._version, response) + + async def page_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, + ) -> ContentPage: + """ + Asynchronously retrieve a single page of ContentInstance records from the API. + Request is executed immediately + + :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: Page of ContentInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentPage: + """ + Asynchronously retrieve a specific page of ContentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/content/v2/content_and_approvals.py b/twilio/rest/content/v2/content_and_approvals.py new file mode 100644 index 0000000000..e383867e93 --- /dev/null +++ b/twilio/rest/content/v2/content_and_approvals.py @@ -0,0 +1,802 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Content + 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_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ContentAndApprovalsInstance(InstanceResource): + """ + :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 sid: The unique string that that we created to identify the Content resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/usage/api/account) that created Content resource. + :ivar friendly_name: A string name used to describe the Content resource. Not visible to the end recipient. + :ivar language: Two-letter (ISO 639-1) language code (e.g., en) identifying the language the Content resource is in. + :ivar variables: Defines the default placeholder values for variables included in the Content resource. e.g. {\"1\": \"Customer_Name\"}. + :ivar types: The [Content types](https://www.twilio.com/docs/content/content-types-overview) (e.g. twilio/text) for this Content resource. + :ivar approval_requests: The submitted information and approval request status of the Content resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + 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.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.language: Optional[str] = payload.get("language") + self.variables: Optional[Dict[str, object]] = payload.get("variables") + self.types: Optional[Dict[str, object]] = payload.get("types") + self.approval_requests: Optional[Dict[str, object]] = payload.get( + "approval_requests" + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ContentAndApprovalsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ContentAndApprovalsInstance: + """ + Build an instance of ContentAndApprovalsInstance + + :param payload: Payload response from the API + """ + + return ContentAndApprovalsInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ContentAndApprovalsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ContentAndApprovalsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ContentAndApprovals" + + def stream( + 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, + ) -> Iterator[ContentAndApprovalsInstance]: + """ + Streams ContentAndApprovalsInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + 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"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_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, + ) -> AsyncIterator[ContentAndApprovalsInstance]: + """ + Asynchronously streams ContentAndApprovalsInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_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"], + ) + + 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, + 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, + ) -> List[ContentAndApprovalsInstance]: + """ + Lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + 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, + ) + ) + + async def list_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, + ) -> List[ContentAndApprovalsInstance]: + """ + Asynchronously lists ContentAndApprovalsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_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, + ) + ] + + 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, + 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, + ) -> ContentAndApprovalsPage: + """ + Retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :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: Page of ContentAndApprovalsInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ContentAndApprovalsPage(self._version, response) + + async def page_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, + ) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a single page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :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: Page of ContentAndApprovalsInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + async def get_page_async(self, target_url: str) -> ContentAndApprovalsPage: + """ + Asynchronously retrieve a specific page of ContentAndApprovalsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ContentAndApprovalsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ContentAndApprovalsPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/ConversationsBase.py b/twilio/rest/conversations/ConversationsBase.py index 06d5533e3e..0a34545412 100644 --- a/twilio/rest/conversations/ConversationsBase.py +++ b/twilio/rest/conversations/ConversationsBase.py @@ -14,9 +14,11 @@ 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): + def __init__(self, twilio: Client): """ Initialize the Conversations Domain @@ -25,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: @@ -35,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/__init__.py b/twilio/rest/conversations/v1/__init__.py index 0fbe314fa2..1ec6c22a7b 100644 --- a/twilio/rest/conversations/v1/__init__.py +++ b/twilio/rest/conversations/v1/__init__.py @@ -18,6 +18,9 @@ from twilio.rest.conversations.v1.address_configuration import AddressConfigurationList from twilio.rest.conversations.v1.configuration import ConfigurationList from twilio.rest.conversations.v1.conversation import ConversationList +from twilio.rest.conversations.v1.conversation_with_participants import ( + ConversationWithParticipantsList, +) from twilio.rest.conversations.v1.credential import CredentialList from twilio.rest.conversations.v1.participant_conversation import ( ParticipantConversationList, @@ -28,6 +31,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Conversations @@ -38,6 +42,9 @@ def __init__(self, domain: Domain): self._address_configurations: Optional[AddressConfigurationList] = None self._configuration: Optional[ConfigurationList] = None self._conversations: Optional[ConversationList] = None + self._conversation_with_participants: Optional[ + ConversationWithParticipantsList + ] = None self._credentials: Optional[CredentialList] = None self._participant_conversations: Optional[ParticipantConversationList] = None self._roles: Optional[RoleList] = None @@ -62,6 +69,14 @@ def conversations(self) -> ConversationList: self._conversations = ConversationList(self) return self._conversations + @property + def conversation_with_participants(self) -> ConversationWithParticipantsList: + if self._conversation_with_participants is None: + self._conversation_with_participants = ConversationWithParticipantsList( + self + ) + return self._conversation_with_participants + @property def credentials(self) -> CredentialList: if self._credentials is None: diff --git a/twilio/rest/conversations/v1/address_configuration.py b/twilio/rest/conversations/v1/address_configuration.py index 05bc008151..3c0864ec2f 100644 --- a/twilio/rest/conversations/v1/address_configuration.py +++ b/twilio/rest/conversations/v1/address_configuration.py @@ -12,10 +12,10 @@ 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 @@ -24,20 +24,25 @@ class AddressConfigurationInstance(InstanceResource): + class AutoCreationType(object): WEBHOOK = "webhook" STUDIO = "studio" DEFAULT = "default" class Method(object): - GET = "GET" - POST = "POST" + GET = "get" + POST = "post" class Type(object): SMS = "sms" WHATSAPP = "whatsapp" MESSENGER = "messenger" GBM = "gbm" + EMAIL = "email" + RCS = "rcs" + APPLE = "apple" + CHAT = "chat" """ :ivar sid: A 34 character string that uniquely identifies this resource. @@ -49,6 +54,7 @@ class Type(object): :ivar date_created: The date that this resource was created. :ivar date_updated: The date that this resource was last updated. :ivar url: An absolute API resource URL for this address configuration. + :ivar address_country: An ISO 3166-1 alpha-2n country code which the address belongs to. This is currently only applicable to short code addresses. """ def __init__( @@ -69,10 +75,12 @@ def __init__( payload.get("date_updated") ) self.url: Optional[str] = payload.get("url") + self.address_country: Optional[str] = payload.get("address_country") self._solution = { "sid": sid or self.sid, } + self._context: Optional[AddressConfigurationContext] = None @property @@ -108,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 @@ -126,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, @@ -212,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 @@ -225,6 +355,7 @@ def __repr__(self) -> str: class AddressConfigurationContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the AddressConfigurationContext @@ -240,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 @@ -247,9 +392,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -259,9 +426,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AddressConfigurationInstance 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) -> AddressConfigurationInstance: @@ -271,17 +462,43 @@ def fetch(self) -> AddressConfigurationInstance: :returns: The fetched AddressConfigurationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AddressConfigurationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AddressConfigurationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AddressConfigurationInstance: """ @@ -290,19 +507,29 @@ async def fetch_async(self) -> AddressConfigurationInstance: :returns: The fetched AddressConfigurationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AddressConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AddressConfigurationInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, auto_creation_enabled: Union[bool, object] = values.unset, @@ -317,26 +544,20 @@ 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( { "FriendlyName": friendly_name, - "AutoCreation.Enabled": auto_creation_enabled, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), "AutoCreation.Type": auto_creation_type, "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, "AutoCreation.WebhookUrl": auto_creation_webhook_url, @@ -348,18 +569,17 @@ def update( "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AddressConfigurationInstance( - self._version, payload, sid=self._solution["sid"] + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) - async def update_async( + def update( self, friendly_name: Union[str, object] = values.unset, auto_creation_enabled: Union[bool, object] = values.unset, @@ -376,7 +596,7 @@ async def update_async( auto_creation_studio_retry_count: Union[int, object] = values.unset, ) -> AddressConfigurationInstance: """ - Asynchronous coroutine to update the 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 @@ -390,78 +610,23 @@ async def update_async( :returns: The updated AddressConfigurationInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "AutoCreation.Enabled": auto_creation_enabled, - "AutoCreation.Type": auto_creation_type, - "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, - "AutoCreation.WebhookUrl": auto_creation_webhook_url, - "AutoCreation.WebhookMethod": auto_creation_webhook_method, - "AutoCreation.WebhookFilters": serialize.map( - auto_creation_webhook_filters, lambda e: e - ), - "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, - "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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"] ) - 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 AddressConfigurationPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> AddressConfigurationInstance: - """ - Build an instance of AddressConfigurationInstance - - :param payload: Payload response from the API - """ - return AddressConfigurationInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class AddressConfigurationList(ListResource): - def __init__(self, version: Version): - """ - Initialize the AddressConfigurationList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Configuration/Addresses" - - def create( + def update_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[ @@ -475,12 +640,10 @@ def create( 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: """ - Create the AddressConfigurationInstance + Update 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: @@ -491,14 +654,409 @@ def create( :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 = 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( + { + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + } + ) + 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, + 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 + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AddressConfigurationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AddressConfigurationInstance: + """ + Build an instance of AddressConfigurationInstance + + :param payload: Payload response from the API + """ + + return AddressConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AddressConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AddressConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Configuration/Addresses" + + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Type": type, + "Address": address, + "FriendlyName": friendly_name, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), + "AutoCreation.Type": auto_creation_type, + "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, + "AutoCreation.WebhookUrl": auto_creation_webhook_url, + "AutoCreation.WebhookMethod": auto_creation_webhook_method, + "AutoCreation.WebhookFilters": serialize.map( + auto_creation_webhook_filters, lambda e: e + ), + "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, + "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + "AddressCountry": address_country, + } + ) + 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: "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: + """ + 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, _, _ = 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( { "Type": type, "Address": address, "FriendlyName": friendly_name, - "AutoCreation.Enabled": auto_creation_enabled, + "AutoCreation.Enabled": serialize.boolean_to_string( + auto_creation_enabled + ), "AutoCreation.Type": auto_creation_type, "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, "AutoCreation.WebhookUrl": auto_creation_webhook_url, @@ -508,16 +1066,18 @@ def create( ), "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, + "AddressCountry": address_country, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AddressConfigurationInstance(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, @@ -536,6 +1096,7 @@ async def create_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, + address_country: Union[str, object] = values.unset, ) -> AddressConfigurationInstance: """ Asynchronously create the AddressConfigurationInstance @@ -551,34 +1112,79 @@ async def create_async( :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 """ - data = values.of( - { - "Type": type, - "Address": address, - "FriendlyName": friendly_name, - "AutoCreation.Enabled": auto_creation_enabled, - "AutoCreation.Type": auto_creation_type, - "AutoCreation.ConversationServiceSid": auto_creation_conversation_service_sid, - "AutoCreation.WebhookUrl": auto_creation_webhook_url, - "AutoCreation.WebhookMethod": auto_creation_webhook_method, - "AutoCreation.WebhookFilters": serialize.map( - auto_creation_webhook_filters, lambda e: e - ), - "AutoCreation.StudioFlowSid": auto_creation_studio_flow_sid, - "AutoCreation.StudioRetryCount": auto_creation_studio_retry_count, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return AddressConfigurationInstance(self._version, payload) + :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, @@ -634,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, @@ -655,6 +1317,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -684,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( @@ -693,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, @@ -720,7 +1440,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 AddressConfigurationPage(self._version, response) async def page_async( @@ -750,11 +1476,91 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 d4bd2ad394..ec2a73badd 100644 --- a/twilio/rest/conversations/v1/configuration/__init__.py +++ b/twilio/rest/conversations/v1/configuration/__init__.py @@ -12,9 +12,9 @@ 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 @@ -24,11 +24,10 @@ class ConfigurationInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this configuration. :ivar default_chat_service_sid: The SID of the default [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) used when creating a conversation. - :ivar default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/sms/services/api) used when creating a conversation. + :ivar default_messaging_service_sid: The SID of the default [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) used when creating a conversation. :ivar default_inactive_timer: Default ISO8601 duration when conversation will be switched to `inactive` state. Minimum value for this timer is 1 minute. :ivar default_closed_timer: Default ISO8601 duration when conversation will be switched to `closed` state. Minimum value for this timer is 10 minutes. :ivar url: An absolute API resource URL for this global configuration. @@ -86,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, @@ -97,7 +114,7 @@ def update( 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/sms/services/api) 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. @@ -121,7 +138,7 @@ async def update_async( 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/sms/services/api) 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. @@ -134,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 @@ -145,6 +210,7 @@ def __repr__(self) -> str: class ConfigurationContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the ConfigurationContext @@ -155,6 +221,22 @@ def __init__(self, version: Version): self._uri = "/Configuration" + 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 @@ -162,16 +244,41 @@ def fetch(self) -> ConfigurationInstance: :returns: The fetched ConfigurationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ConfigurationInstance( + self._version, + payload, ) - return ConfigurationInstance( + 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, ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + async 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: """ @@ -180,16 +287,57 @@ async def fetch_async(self) -> ConfigurationInstance: :returns: The fetched ConfigurationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ConfigurationInstance( + self._version, + payload, ) - return ConfigurationInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "DefaultChatServiceSid": default_chat_service_sid, + "DefaultMessagingServiceSid": default_messaging_service_sid, + "DefaultInactiveTimer": default_inactive_timer, + "DefaultClosedTimer": default_closed_timer, + } + ) + 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, @@ -202,12 +350,60 @@ def update( 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/sms/services/api) 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, _, _ = 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( { "DefaultChatServiceSid": default_chat_service_sid, @@ -216,14 +412,15 @@ def update( "DefaultClosedTimer": default_closed_timer, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ConfigurationInstance(self._version, payload) + 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, @@ -236,28 +433,45 @@ async def update_async( 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/sms/services/api) 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 """ - data = values.of( - { - "DefaultChatServiceSid": default_chat_service_sid, - "DefaultMessagingServiceSid": default_messaging_service_sid, - "DefaultInactiveTimer": default_inactive_timer, - "DefaultClosedTimer": default_closed_timer, - } + 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) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return ConfigurationInstance(self._version, payload) + :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: """ @@ -270,6 +484,7 @@ def __repr__(self) -> str: class ConfigurationList(ListResource): + def __init__(self, version: Version): """ Initialize the ConfigurationList diff --git a/twilio/rest/conversations/v1/configuration/webhook.py b/twilio/rest/conversations/v1/configuration/webhook.py index 4b2f1c1d7c..d286bba936 100644 --- a/twilio/rest/conversations/v1/configuration/webhook.py +++ b/twilio/rest/conversations/v1/configuration/webhook.py @@ -12,9 +12,9 @@ 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 @@ -22,6 +22,7 @@ class WebhookInstance(InstanceResource): + class Method(object): GET = "GET" POST = "POST" @@ -33,7 +34,7 @@ class Target(object): """ :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. :ivar method: - :ivar filters: The list of webhook event triggers that are enabled for this Service: `onMessageAdded`, `onMessageUpdated`, `onMessageRemoved`, `onConversationUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved` + :ivar 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` :ivar pre_webhook_url: The absolute url the pre-event webhook request should be sent to. :ivar post_webhook_url: The absolute url the post-event webhook request should be sent to. :ivar target: @@ -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, @@ -97,7 +116,7 @@ def update( 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`, `onConversationUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved` + :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: @@ -124,7 +143,7 @@ async def update_async( 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`, `onConversationUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved` + :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: @@ -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 @@ -150,6 +223,7 @@ def __repr__(self) -> str: class WebhookContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the WebhookContext @@ -160,6 +234,22 @@ def __init__(self, version: Version): self._uri = "/Configuration/Webhooks" + 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) -> WebhookInstance: """ Fetch the WebhookInstance @@ -167,16 +257,41 @@ def fetch(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, ) - return WebhookInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WebhookInstance: """ @@ -185,16 +300,59 @@ async def fetch_async(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, ) - return WebhookInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Method": method, + "Filters": serialize.map(filters, lambda e: e), + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Target": target, + } + ) + 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, @@ -208,13 +366,66 @@ def update( 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`, `onConversationUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved` + :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, _, _ = 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( { "Method": method, @@ -224,14 +435,15 @@ def update( "Target": target, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WebhookInstance(self._version, payload) + 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, @@ -245,30 +457,50 @@ async def update_async( 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`, `onConversationUpdated`, `onConversationRemoved`, `onParticipantAdded`, `onParticipantUpdated`, `onParticipantRemoved` + :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 """ - data = values.of( - { - "Method": method, - "Filters": serialize.map(filters, lambda e: e), - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "Target": target, - } + 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) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return WebhookInstance(self._version, payload) + :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: """ @@ -281,6 +513,7 @@ def __repr__(self) -> str: class WebhookList(ListResource): + def __init__(self, version: Version): """ Initialize the WebhookList diff --git a/twilio/rest/conversations/v1/conversation/__init__.py b/twilio/rest/conversations/v1/conversation/__init__.py index aee3bc7c6f..808ab297e8 100644 --- a/twilio/rest/conversations/v1/conversation/__init__.py +++ b/twilio/rest/conversations/v1/conversation/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,9 @@ class ConversationInstance(InstanceResource): + class State(object): + INITIALIZING = "initializing" INACTIVE = "inactive" ACTIVE = "active" CLOSED = "closed" @@ -39,7 +41,7 @@ class WebhookEnabledType(object): """ :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. - :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/sms/services/api) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. :ivar sid: A 34 character string that uniquely identifies this resource. :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. :ivar 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. @@ -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[ @@ -163,6 +218,8 @@ def update( 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": """ Update the ConversationInstance @@ -172,11 +229,13 @@ def update( :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/sms/services/api) this conversation belongs to. + :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 """ @@ -191,6 +250,8 @@ def update( 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_async( @@ -207,6 +268,8 @@ async def update_async( 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 @@ -216,11 +279,13 @@ async def update_async( :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/sms/services/api) this conversation belongs to. + :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 """ @@ -235,6 +300,108 @@ async def update_async( timers_inactive=timers_inactive, timers_closed=timers_closed, unique_name=unique_name, + bindings_email_address=bindings_email_address, + 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 @@ -269,6 +436,7 @@ def __repr__(self) -> str: class ConversationContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ConversationContext @@ -288,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[ @@ -301,13 +493,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -322,14 +551,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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: @@ -339,17 +597,43 @@ def fetch(self) -> ConversationInstance: :returns: The fetched ConversationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ConversationInstance( + 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, 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) -> ConversationInstance: """ @@ -358,19 +642,29 @@ async def fetch_async(self) -> ConversationInstance: :returns: The fetched ConversationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ConversationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ConversationInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -384,23 +678,16 @@ def update( timers_inactive: Union[str, object] = values.unset, timers_closed: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> 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/sms/services/api) 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. + Internal helper for update operation - :returns: The updated ConversationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -412,21 +699,30 @@ def update( "Timers.Inactive": timers_inactive, "Timers.Closed": timers_closed, "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + 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" - payload = self._version.update( + headers["Accept"] = "application/json" + + 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 @@ -440,48 +736,260 @@ async def update_async( 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 + 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/sms/services/api) this conversation belongs to. + :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 """ - 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, - "UniqueName": unique_name, - } + 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, ) - headers = values.of( + return ConversationInstance(self._version, payload, 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, 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( { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "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, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, } ) + 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 - payload = await self._version.update_async( + 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[ + "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: """ @@ -529,12 +1037,14 @@ def __repr__(self) -> str: class ConversationPage(Page): + 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: @@ -547,6 +1057,7 @@ def __repr__(self) -> str: class ConversationList(ListResource): + def __init__(self, version: Version): """ Initialize the ConversationList @@ -558,7 +1069,7 @@ def __init__(self, version: Version): self._uri = "/Conversations" - def create( + def _create( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -572,23 +1083,16 @@ def create( state: Union["ConversationInstance.State", object] = values.unset, timers_inactive: Union[str, object] = values.unset, timers_closed: Union[str, object] = values.unset, - ) -> ConversationInstance: + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: """ - 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/sms/services/api) 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. + Internal helper for create operation - :returns: The created ConversationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -600,20 +1104,26 @@ def create( "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", } ) - payload = self._version.create( + + 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 ) - return ConversationInstance(self._version, payload) - - async def create_async( + def create( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -627,23 +1137,119 @@ async def create_async( 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 + 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/sms/services/api) this conversation belongs to. + :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: 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( { "FriendlyName": friendly_name, @@ -655,19 +1261,128 @@ async def create_async( "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", } ) - payload = await self._version.create_async( + + 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, + 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. + + :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_with_http_info_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, + ) -> ApiResponse: + """ + 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. + :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 = 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, + ) + instance = ConversationInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + def stream( self, start_date: Union[str, object] = values.unset, @@ -682,8 +1397,8 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param str end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -718,8 +1433,8 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param str end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -740,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, @@ -753,8 +1538,8 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param str end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -765,6 +1550,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( start_date=start_date, @@ -788,8 +1574,8 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param str end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -800,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( @@ -811,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, @@ -824,8 +1679,8 @@ def page( Retrieve a single page of ConversationInstance records from the API. Request is executed immediately - :param start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -844,7 +1699,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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) async def page_async( @@ -860,8 +1721,8 @@ async def page_async( Asynchronously retrieve a single page of ConversationInstance records from the API. Request is executed immediately - :param start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -880,11 +1741,103 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 a4a06c093b..4d1345715e 100644 --- a/twilio/rest/conversations/v1/conversation/message/__init__.py +++ b/twilio/rest/conversations/v1/conversation/message/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,6 +27,7 @@ class MessageInstance(InstanceResource): + class OrderType(object): ASC = "asc" DESC = "desc" @@ -50,7 +51,7 @@ class WebhookEnabledType(object): :ivar url: An absolute API resource API URL for this message. :ivar delivery: An object that contains the summary of delivery statuses for the message to non-chat participants. :ivar links: Contains an absolute API resource URL to access the delivery & read receipts of this message. - :ivar content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content-api) template. + :ivar content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template. """ def __init__( @@ -68,7 +69,7 @@ def __init__( self.index: Optional[int] = deserialize.integer(payload.get("index")) self.author: Optional[str] = payload.get("author") self.body: Optional[str] = payload.get("body") - self.media: Optional[List[object]] = payload.get("media") + self.media: Optional[List[Dict[str, object]]] = payload.get("media") self.attributes: Optional[str] = payload.get("attributes") self.participant_sid: Optional[str] = payload.get("participant_sid") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( @@ -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[ @@ -166,6 +220,7 @@ def update( 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": """ Update the MessageInstance @@ -176,6 +231,7 @@ def update( :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. :returns: The updated MessageInstance """ @@ -186,6 +242,7 @@ def update( date_created=date_created, date_updated=date_updated, attributes=attributes, + subject=subject, ) async def update_async( @@ -198,6 +255,7 @@ async def update_async( 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 @@ -208,6 +266,7 @@ async def update_async( :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. :returns: The updated MessageInstance """ @@ -218,6 +277,77 @@ async def update_async( date_created=date_created, date_updated=date_updated, attributes=attributes, + 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. + :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. + + :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. + :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. + + :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 @@ -238,6 +368,7 @@ def __repr__(self) -> str: class MessageContext(InstanceContext): + def __init__(self, version: Version, conversation_sid: str, sid: str): """ Initialize the MessageContext @@ -259,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[ @@ -272,13 +427,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -293,14 +485,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> MessageInstance: @@ -310,18 +531,45 @@ def fetch(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MessageInstance: """ @@ -330,20 +578,31 @@ async def fetch_async(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MessageInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -353,19 +612,15 @@ def update( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + subject: Union[str, object] = values.unset, + ) -> 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. + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Author": author, @@ -373,26 +628,29 @@ def update( "DateCreated": serialize.iso8601_datetime(date_created), "DateUpdated": serialize.iso8601_datetime(date_updated), "Attributes": attributes, + "Subject": subject, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return MessageInstance( - self._version, - payload, - conversation_sid=self._solution["conversation_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -402,9 +660,10 @@ async def update_async( 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 + 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`. @@ -412,28 +671,19 @@ async def update_async( :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. :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, - } - ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - - 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, @@ -441,16 +691,189 @@ 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: """ - if self._delivery_receipts is None: - self._delivery_receipts = DeliveryReceiptList( - self._version, - self._solution["conversation_sid"], - self._solution["sid"], + 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. + :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. + + :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. + :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. + + :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. + :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. + + :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( + self._version, + self._solution["conversation_sid"], + self._solution["sid"], ) return self._delivery_receipts @@ -465,12 +888,14 @@ def __repr__(self) -> str: 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, conversation_sid=self._solution["conversation_sid"] ) @@ -485,6 +910,7 @@ def __repr__(self) -> str: class MessageList(ListResource): + def __init__(self, version: Version, conversation_sid: str): """ Initialize the MessageList @@ -503,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 @@ -516,22 +942,15 @@ def create( media_sid: Union[str, object] = values.unset, content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, - ) -> MessageInstance: + subject: Union[str, object] = values.unset, + ) -> 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-api) 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. - - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Author": author, @@ -542,22 +961,72 @@ def create( "MediaSid": media_sid, "ContentSid": content_sid, "ContentVariables": content_variables, + "Subject": subject, } ) headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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[ + "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. + :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 + """ + 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 @@ -570,9 +1039,10 @@ async def create_async( media_sid: Union[str, object] = values.unset, content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, - ) -> MessageInstance: + subject: Union[str, object] = values.unset, + ) -> 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`. @@ -581,11 +1051,51 @@ async def create_async( :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-api) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :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( { "Author": author, @@ -596,21 +1106,119 @@ async def create_async( "MediaSid": media_sid, "ContentSid": content_sid, "ContentVariables": content_variables, + "Subject": subject, } ) headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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. + :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 + """ + 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. + :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: 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, @@ -665,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, @@ -686,6 +1350,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -715,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( @@ -724,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, @@ -751,8 +1473,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MessagePage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -781,10 +1509,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MessagePage(self._version, response, self._solution) + 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: """ @@ -796,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: """ @@ -808,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 3949c67032..ffebce0840 100644 --- a/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py +++ b/twilio/rest/conversations/v1/conversation/message/delivery_receipt.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class DeliveryReceiptInstance(InstanceResource): + class DeliveryStatus(object): READ = "read" FAILED = "failed" @@ -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 @@ -126,6 +146,7 @@ def __repr__(self) -> str: class DeliveryReceiptContext(InstanceContext): + def __init__( self, version: Version, conversation_sid: str, message_sid: str, sid: str ): @@ -149,6 +170,22 @@ def __init__( **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) -> DeliveryReceiptInstance: """ Fetch the DeliveryReceiptInstance @@ -156,19 +193,47 @@ def fetch(self) -> DeliveryReceiptInstance: :returns: The fetched DeliveryReceiptInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], ) - return DeliveryReceiptInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> DeliveryReceiptInstance: """ @@ -177,19 +242,31 @@ async def fetch_async(self) -> DeliveryReceiptInstance: :returns: The fetched DeliveryReceiptInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return DeliveryReceiptInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + message_sid=self._solution["message_sid"], + sid=self._solution["sid"], ) - return DeliveryReceiptInstance( + 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: """ @@ -202,12 +279,14 @@ def __repr__(self) -> str: class DeliveryReceiptPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: """ Build an instance of DeliveryReceiptInstance :param payload: Payload response from the API """ + return DeliveryReceiptInstance( self._version, payload, @@ -225,6 +304,7 @@ def __repr__(self) -> str: class DeliveryReceiptList(ListResource): + def __init__(self, version: Version, conversation_sid: str, message_sid: str): """ Initialize the DeliveryReceiptList @@ -297,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, @@ -316,6 +446,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -342,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( @@ -350,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, @@ -374,8 +556,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DeliveryReceiptPage(self._version, response, self._solution) + 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 DeliveryReceiptPage(self._version, response, solution=self._solution) async def page_async( self, @@ -401,10 +589,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return DeliveryReceiptPage(self._version, response, self._solution) + 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: """ @@ -416,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: """ @@ -428,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 e9cb028ff3..0600512c97 100644 --- a/twilio/rest/conversations/v1/conversation/participant.py +++ b/twilio/rest/conversations/v1/conversation/participant.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class ParticipantInstance(InstanceResource): + class WebhookEnabledType(object): TRUE = "true" FALSE = "false" @@ -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 @@ -246,6 +388,7 @@ def __repr__(self) -> str: class ParticipantContext(InstanceContext): + def __init__(self, version: Version, conversation_sid: str, sid: str): """ Initialize the ParticipantContext @@ -265,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[ @@ -278,13 +445,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -299,14 +503,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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: @@ -316,18 +549,45 @@ def fetch(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return ParticipantInstance( + 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_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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ParticipantInstance: """ @@ -336,20 +596,31 @@ async def fetch_async(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return ParticipantInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -363,23 +634,14 @@ 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( { "DateCreated": serialize.iso8601_datetime(date_created), @@ -393,24 +655,26 @@ def update( "LastReadTimestamp": last_read_timestamp, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return ParticipantInstance( - self._version, - payload, - conversation_sid=self._solution["conversation_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -426,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. @@ -441,29 +705,173 @@ async def update_async( :returns: The updated ParticipantInstance """ - 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, - "Identity": identity, - "LastReadMessageIndex": last_read_message_index, - "LastReadTimestamp": last_read_timestamp, - } - ) - headers = values.of( + 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"], + ) + + 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( { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "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, + "Identity": identity, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, } ) + 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" - payload = await self._version.update_async( + 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[ + "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, @@ -471,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 @@ -482,12 +941,14 @@ def __repr__(self) -> str: class ParticipantPage(Page): + 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_sid=self._solution["conversation_sid"] ) @@ -502,6 +963,7 @@ def __repr__(self) -> str: class ParticipantList(ListResource): + def __init__(self, version: Version, conversation_sid: str): """ Initialize the ParticipantList @@ -520,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 @@ -533,22 +995,14 @@ 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( { "Identity": identity, @@ -564,17 +1018,63 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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[ + "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 @@ -587,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. @@ -601,8 +1101,45 @@ 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( { "Identity": identity, @@ -618,16 +1155,107 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -678,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, @@ -697,6 +1375,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -723,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( @@ -731,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, @@ -755,8 +1485,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ParticipantPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -782,10 +1518,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ParticipantPage(self._version, response, self._solution) + 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: """ @@ -797,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: """ @@ -809,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 8b7493388a..3140fd846c 100644 --- a/twilio/rest/conversations/v1/conversation/webhook.py +++ b/twilio/rest/conversations/v1/conversation/webhook.py @@ -12,10 +12,10 @@ 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 @@ -24,9 +24,10 @@ 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 @@ -189,6 +281,7 @@ def __repr__(self) -> str: class WebhookContext(InstanceContext): + def __init__(self, version: Version, conversation_sid: str, sid: str): """ Initialize the WebhookContext @@ -208,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 @@ -215,9 +322,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -227,9 +356,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance 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) -> WebhookInstance: @@ -239,18 +392,45 @@ def fetch(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WebhookInstance: """ @@ -259,38 +439,45 @@ async def fetch_async(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + 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( + 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( { "Configuration.Url": configuration_url, @@ -304,13 +491,42 @@ def update( "Configuration.FlowSid": configuration_flow_sid, } ) + 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, + 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, @@ -318,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: @@ -335,8 +551,38 @@ 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( { "Configuration.Url": configuration_url, @@ -350,13 +596,42 @@ async def update_async( "Configuration.FlowSid": configuration_flow_sid, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -364,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 @@ -375,12 +684,14 @@ def __repr__(self) -> str: class WebhookPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: """ Build an instance of WebhookInstance :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, conversation_sid=self._solution["conversation_sid"] ) @@ -395,6 +706,7 @@ def __repr__(self) -> str: class WebhookList(ListResource): + def __init__(self, version: Version, conversation_sid: str): """ Initialize the WebhookList @@ -413,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, @@ -422,20 +734,14 @@ 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( { "Target": target, @@ -451,18 +757,53 @@ def create( "Configuration.ReplayAfter": configuration_replay_after, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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: "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, @@ -471,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. @@ -483,8 +824,39 @@ 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( { "Target": target, @@ -500,17 +872,89 @@ async def create_async( "Configuration.ReplayAfter": configuration_replay_after, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -561,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, @@ -580,6 +1074,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -606,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( @@ -614,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, @@ -638,8 +1184,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return WebhookPage(self._version, response, self._solution) + 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 WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -665,10 +1217,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return WebhookPage(self._version, response, self._solution) + 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: """ @@ -680,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: """ @@ -692,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 new file mode 100644 index 0000000000..76e25061e5 --- /dev/null +++ b/twilio/rest/conversations/v1/conversation_with_participants.py @@ -0,0 +1,449 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + 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 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 ConversationWithParticipantsInstance(InstanceResource): + + class State(object): + INITIALIZING = "initializing" + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar 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. + :ivar 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. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + :ivar url: An absolute API resource URL for this conversation. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationWithParticipantsInstance.State"] = ( + payload.get("state") + ) + 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.timers: Optional[Dict[str, object]] = payload.get("timers") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ConversationWithParticipantsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ConversationWithParticipantsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ConversationWithParticipants" + + 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, + ) -> 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, + "Participant": serialize.map(participant, lambda e: e), + } + ) + 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[ + "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) + + 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( + { + "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, + "Participant": serialize.map(participant, lambda e: e), + } + ) + 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 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v1/credential.py b/twilio/rest/conversations/v1/credential.py index 0b6dfd8289..a1aabe7bdd 100644 --- a/twilio/rest/conversations/v1/credential.py +++ b/twilio/rest/conversations/v1/credential.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class CredentialInstance(InstanceResource): + class PushType(object): APN = "apn" GCM = "gcm" @@ -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 @@ -191,6 +295,7 @@ def __repr__(self) -> str: class CredentialContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CredentialContext @@ -206,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 @@ -213,9 +332,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -225,9 +366,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance 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) -> CredentialInstance: @@ -237,17 +402,43 @@ def fetch(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialInstance: """ @@ -256,19 +447,29 @@ async def fetch_async(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + 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( + def _update( self, type: Union["CredentialInstance.PushType", object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -277,41 +478,36 @@ 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 - - :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 update operation - :returns: The updated CredentialInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Type": type, "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - async def update_async( + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( self, type: Union["CredentialInstance.PushType", object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -322,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. @@ -334,78 +530,29 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "Type": type, - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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. @@ -415,31 +562,61 @@ 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( { "Type": type, "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(self._version, payload) + headers["Accept"] = "application/json" - async def create_async( + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) + + async def update_async( 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, @@ -448,7 +625,7 @@ async def create_async( secret: Union[str, object] = values.unset, ) -> CredentialInstance: """ - Asynchronously create the 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. @@ -458,28 +635,311 @@ async def create_async( :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: 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) + + 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": sandbox, + "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, + 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: + """ + 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, _, _ = 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( + { + "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" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -530,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, @@ -549,6 +1059,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -575,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( @@ -583,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, @@ -607,7 +1169,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CredentialPage(self._version, response) async def page_async( @@ -634,11 +1202,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 0a7d0634b9..9d6fc2566b 100644 --- a/twilio/rest/conversations/v1/participant_conversation.py +++ b/twilio/rest/conversations/v1/participant_conversation.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +24,7 @@ class ParticipantConversationInstance(InstanceResource): + class State(object): INACTIVE = "inactive" ACTIVE = "active" @@ -69,18 +70,18 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.conversation_attributes: Optional[str] = payload.get( "conversation_attributes" ) - self.conversation_date_created: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("conversation_date_created")) - self.conversation_date_updated: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("conversation_date_updated")) + self.conversation_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_created")) + ) + self.conversation_date_updated: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_updated")) + ) self.conversation_created_by: Optional[str] = payload.get( "conversation_created_by" ) - self.conversation_state: Optional[ - "ParticipantConversationInstance.State" - ] = payload.get("conversation_state") + self.conversation_state: Optional["ParticipantConversationInstance.State"] = ( + payload.get("conversation_state") + ) self.conversation_timers: Optional[Dict[str, object]] = payload.get( "conversation_timers" ) @@ -97,12 +98,14 @@ def __repr__(self) -> str: class ParticipantConversationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstance: """ Build an instance of ParticipantConversationInstance :param payload: Payload response from the API """ + return ParticipantConversationInstance(self._version, payload) def __repr__(self) -> str: @@ -115,6 +118,7 @@ def __repr__(self) -> str: class ParticipantConversationList(ListResource): + def __init__(self, version: Version): """ Initialize the ParticipantConversationList @@ -188,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, @@ -211,6 +275,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -243,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( @@ -253,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, @@ -283,7 +411,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 ParticipantConversationPage(self._version, response) async def page_async( @@ -316,11 +450,97 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 fb7626ce0c..f0e9160bf5 100644 --- a/twilio/rest/conversations/v1/role.py +++ b/twilio/rest/conversations/v1/role.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class RoleInstance(InstanceResource): + class RoleType(object): CONVERSATION = "conversation" SERVICE = "service" @@ -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 @@ -150,6 +212,7 @@ def __repr__(self) -> str: class RoleContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the RoleContext @@ -165,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 @@ -172,9 +249,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -184,9 +283,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance 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) -> RoleInstance: @@ -196,17 +319,43 @@ def fetch(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RoleInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RoleInstance: """ @@ -215,62 +364,120 @@ async def fetch_async(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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 @@ -282,12 +489,14 @@ def __repr__(self) -> str: class RolePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: """ Build an instance of RoleInstance :param payload: Payload response from the API """ + return RoleInstance(self._version, payload) def __repr__(self) -> str: @@ -300,6 +509,7 @@ def __repr__(self) -> str: class RoleList(ListResource): + def __init__(self, version: Version): """ Initialize the RoleList @@ -311,6 +521,33 @@ def __init__(self, version: Version): self._uri = "/Roles" + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: 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.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: @@ -323,6 +560,39 @@ def create( :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( { "FriendlyName": friendly_name, @@ -330,14 +600,15 @@ def create( "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RoleInstance(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, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] @@ -351,21 +622,28 @@ async def create_async( :returns: The created RoleInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Permission": serialize.map(permission, lambda e: e), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission ) + return RoleInstance(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, type: "RoleInstance.RoleType", permission: List[str] + ) -> ApiResponse: + """ + Asynchronously create the RoleInstance and return response metadata - return RoleInstance(self._version, payload) + :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, @@ -417,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, @@ -436,6 +764,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -462,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( @@ -470,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, @@ -494,7 +874,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 RolePage(self._version, response) async def page_async( @@ -521,11 +907,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 ad4066710f..e4e33fc15e 100644 --- a/twilio/rest/conversations/v1/service/__init__.py +++ b/twilio/rest/conversations/v1/service/__init__.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,9 @@ from twilio.rest.conversations.v1.service.binding import BindingList from twilio.rest.conversations.v1.service.configuration import ConfigurationList from twilio.rest.conversations.v1.service.conversation import ConversationList +from twilio.rest.conversations.v1.service.conversation_with_participants import ( + ConversationWithParticipantsList, +) from twilio.rest.conversations.v1.service.participant_conversation import ( ParticipantConversationList, ) @@ -32,7 +35,6 @@ class ServiceInstance(InstanceResource): - """ :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this service. :ivar sid: A 34 character string that uniquely identifies this resource. @@ -63,6 +65,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -98,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 @@ -116,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: """ @@ -137,6 +176,13 @@ def conversations(self) -> ConversationList: """ return self._proxy.conversations + @property + def conversation_with_participants(self) -> ConversationWithParticipantsList: + """ + Access the conversation_with_participants + """ + return self._proxy.conversation_with_participants + @property def participant_conversations(self) -> ParticipantConversationList: """ @@ -169,6 +215,7 @@ def __repr__(self) -> str: class ServiceContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ServiceContext @@ -187,10 +234,27 @@ def __init__(self, version: Version, sid: str): self._bindings: Optional[BindingList] = None self._configuration: Optional[ConfigurationList] = None self._conversations: Optional[ConversationList] = None + self._conversation_with_participants: Optional[ + ConversationWithParticipantsList + ] = None self._participant_conversations: Optional[ParticipantConversationList] = 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 @@ -198,9 +262,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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: @@ -210,9 +296,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -222,17 +332,43 @@ def fetch(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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: """ @@ -241,17 +377,27 @@ async def fetch_async(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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: @@ -289,6 +435,18 @@ def conversations(self) -> ConversationList: ) return self._conversations + @property + def conversation_with_participants(self) -> ConversationWithParticipantsList: + """ + Access the conversation_with_participants + """ + if self._conversation_with_participants is None: + self._conversation_with_participants = ConversationWithParticipantsList( + self._version, + self._solution["sid"], + ) + return self._conversation_with_participants + @property def participant_conversations(self) -> ParticipantConversationList: """ @@ -336,12 +494,14 @@ def __repr__(self) -> str: 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: @@ -354,6 +514,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -365,50 +526,100 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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) -> 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( { "FriendlyName": friendly_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, + 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, @@ -459,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, @@ -478,6 +739,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -504,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( @@ -512,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, @@ -536,7 +849,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -563,11 +882,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 264ef0490c..095e307625 100644 --- a/twilio/rest/conversations/v1/service/binding.py +++ b/twilio/rest/conversations/v1/service/binding.py @@ -12,10 +12,10 @@ 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 @@ -24,10 +24,12 @@ class BindingInstance(InstanceResource): + 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 @@ -139,6 +178,7 @@ def __repr__(self) -> str: class BindingContext(InstanceContext): + def __init__(self, version: Version, chat_service_sid: str, sid: str): """ Initialize the BindingContext @@ -158,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 @@ -165,9 +219,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -177,9 +253,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance 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) -> BindingInstance: @@ -189,18 +289,45 @@ def fetch(self) -> BindingInstance: :returns: The fetched BindingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], ) - return BindingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> BindingInstance: """ @@ -209,18 +336,29 @@ async def fetch_async(self) -> BindingInstance: :returns: The fetched BindingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return BindingInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], ) - return BindingInstance( + 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: """ @@ -233,12 +371,14 @@ def __repr__(self) -> str: class BindingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: """ Build an instance of BindingInstance :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -253,6 +393,7 @@ def __repr__(self) -> str: class BindingList(ListResource): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the BindingList @@ -282,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 @@ -313,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 @@ -331,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, @@ -343,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 @@ -354,6 +555,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -375,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 @@ -386,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( @@ -396,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, @@ -408,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 @@ -426,8 +691,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return BindingPage(self._version, response, self._solution) + 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 BindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -441,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 @@ -459,10 +730,96 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return BindingPage(self._version, response, self._solution) + 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: """ @@ -474,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: """ @@ -486,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 d5a02443dc..4cdc9de636 100644 --- a/twilio/rest/conversations/v1/service/configuration/__init__.py +++ b/twilio/rest/conversations/v1/service/configuration/__init__.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, Optional, Union -from twilio.base import values +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 @@ -27,15 +27,14 @@ class ConfigurationInstance(InstanceResource): - """ :ivar chat_service_sid: The unique string that we created to identify the Service configuration resource. - :ivar default_conversation_creator_role_sid: The conversation-level role assigned to a conversation creator user when they join a new conversation. See the [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. - :ivar default_conversation_role_sid: The conversation-level role assigned to users when they are added to a conversation. See the [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. - :ivar default_chat_service_role_sid: The service-level role assigned to users when they are added to the service. See the [Conversation Role](https://www.twilio.com/docs/conversations/api/role-resource) for more info about roles. + :ivar 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. + :ivar 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. + :ivar 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. :ivar url: An absolute API resource URL for this service configuration. :ivar links: Contains an absolute API resource URL to access the push notifications configuration of this service. - :ivar reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/chat/reachability-indicator) is enabled for this Conversations Service. The default is `false`. + :ivar reachability_enabled: Whether the [Reachability Indicator](https://www.twilio.com/docs/conversations/reachability) is enabled for this Conversations Service. The default is `false`. """ def __init__( @@ -60,6 +59,7 @@ def __init__( self._solution = { "chat_service_sid": chat_service_sid, } + self._context: Optional[ConfigurationContext] = None @property @@ -95,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, @@ -105,10 +123,10 @@ def update( """ 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 the [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 the [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 the [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/chat/reachability-indicator) is enabled for this Conversations Service. The default is `false`. + :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 """ @@ -129,10 +147,10 @@ async def update_async( """ 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 the [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 the [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 the [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/chat/reachability-indicator) is enabled for this Conversations Service. The default is `false`. + :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 """ @@ -143,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 @@ -154,6 +220,7 @@ def __repr__(self) -> str: class ConfigurationContext(InstanceContext): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the ConfigurationContext @@ -171,6 +238,22 @@ def __init__(self, version: Version, chat_service_sid: str): **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) -> ConfigurationInstance: """ Fetch the ConfigurationInstance @@ -178,17 +261,43 @@ def fetch(self) -> ConfigurationInstance: :returns: The fetched ConfigurationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], ) - return ConfigurationInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ConfigurationInstance: """ @@ -197,90 +306,206 @@ async def fetch_async(self) -> ConfigurationInstance: :returns: The fetched ConfigurationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ConfigurationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], ) - return ConfigurationInstance( + 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( + 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 the [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 the [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 the [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/chat/reachability-indicator) is enabled for this Conversations Service. The default is `false`. - - :returns: The updated ConfigurationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "DefaultConversationCreatorRoleSid": default_conversation_creator_role_sid, "DefaultConversationRoleSid": default_conversation_role_sid, "DefaultChatServiceRoleSid": default_chat_service_role_sid, - "ReachabilityEnabled": reachability_enabled, + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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 the [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 the [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 the [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/chat/reachability-indicator) is enabled for this Conversations Service. The default is `false`. + :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( { "DefaultConversationCreatorRoleSid": default_conversation_creator_role_sid, "DefaultConversationRoleSid": default_conversation_role_sid, "DefaultChatServiceRoleSid": default_chat_service_role_sid, - "ReachabilityEnabled": reachability_enabled, + "ReachabilityEnabled": serialize.boolean_to_string( + reachability_enabled + ), } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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 @@ -292,6 +517,7 @@ def __repr__(self) -> str: class ConfigurationList(ListResource): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the ConfigurationList diff --git a/twilio/rest/conversations/v1/service/configuration/notification.py b/twilio/rest/conversations/v1/service/configuration/notification.py index 388f310e9d..e646dbe7b9 100644 --- a/twilio/rest/conversations/v1/service/configuration/notification.py +++ b/twilio/rest/conversations/v1/service/configuration/notification.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, Optional, Union -from twilio.base import values +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 @@ -22,7 +22,6 @@ class NotificationInstance(InstanceResource): - """ :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this configuration. :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Configuration applies to. @@ -53,6 +52,7 @@ def __init__( self._solution = { "chat_service_sid": chat_service_sid, } + self._context: Optional[NotificationContext] = None @property @@ -88,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, @@ -190,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 @@ -201,6 +321,7 @@ def __repr__(self) -> str: class NotificationContext(InstanceContext): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the NotificationContext @@ -218,6 +339,22 @@ def __init__(self, version: Version, chat_service_sid: str): **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) -> NotificationInstance: """ Fetch the NotificationInstance @@ -225,17 +362,43 @@ def fetch(self) -> NotificationInstance: :returns: The fetched NotificationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], ) - return NotificationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NotificationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> NotificationInstance: """ @@ -244,17 +407,85 @@ async def fetch_async(self) -> NotificationInstance: :returns: The fetched NotificationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return NotificationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], ) - return NotificationInstance( + 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, + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "LogEnabled": serialize.boolean_to_string(log_enabled), + "NewMessage.Enabled": serialize.boolean_to_string(new_message_enabled), + "NewMessage.Template": new_message_template, + "NewMessage.Sound": new_message_sound, + "NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + new_message_badge_count_enabled + ), + "AddedToConversation.Enabled": serialize.boolean_to_string( + added_to_conversation_enabled + ), + "AddedToConversation.Template": added_to_conversation_template, + "AddedToConversation.Sound": added_to_conversation_sound, + "RemovedFromConversation.Enabled": serialize.boolean_to_string( + removed_from_conversation_enabled + ), + "RemovedFromConversation.Template": removed_from_conversation_template, + "RemovedFromConversation.Sound": removed_from_conversation_sound, + "NewMessage.WithMedia.Enabled": serialize.boolean_to_string( + new_message_with_media_enabled + ), + "NewMessage.WithMedia.Template": new_message_with_media_template, + } + ) + 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, @@ -291,32 +522,136 @@ def update( :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"] + ) + + 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 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 = 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( { - "LogEnabled": log_enabled, - "NewMessage.Enabled": new_message_enabled, + "LogEnabled": serialize.boolean_to_string(log_enabled), + "NewMessage.Enabled": serialize.boolean_to_string(new_message_enabled), "NewMessage.Template": new_message_template, "NewMessage.Sound": new_message_sound, - "NewMessage.BadgeCountEnabled": new_message_badge_count_enabled, - "AddedToConversation.Enabled": added_to_conversation_enabled, + "NewMessage.BadgeCountEnabled": serialize.boolean_to_string( + new_message_badge_count_enabled + ), + "AddedToConversation.Enabled": serialize.boolean_to_string( + added_to_conversation_enabled + ), "AddedToConversation.Template": added_to_conversation_template, "AddedToConversation.Sound": added_to_conversation_sound, - "RemovedFromConversation.Enabled": removed_from_conversation_enabled, + "RemovedFromConversation.Enabled": serialize.boolean_to_string( + removed_from_conversation_enabled + ), "RemovedFromConversation.Template": removed_from_conversation_template, "RemovedFromConversation.Sound": removed_from_conversation_sound, - "NewMessage.WithMedia.Enabled": new_message_with_media_enabled, + "NewMessage.WithMedia.Enabled": serialize.boolean_to_string( + new_message_with_media_enabled + ), "NewMessage.WithMedia.Template": new_message_with_media_template, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return NotificationInstance( - self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + 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( @@ -354,33 +689,79 @@ async def update_async( :returns: The updated NotificationInstance """ - data = values.of( - { - "LogEnabled": log_enabled, - "NewMessage.Enabled": new_message_enabled, - "NewMessage.Template": new_message_template, - "NewMessage.Sound": new_message_sound, - "NewMessage.BadgeCountEnabled": new_message_badge_count_enabled, - "AddedToConversation.Enabled": added_to_conversation_enabled, - "AddedToConversation.Template": added_to_conversation_template, - "AddedToConversation.Sound": added_to_conversation_sound, - "RemovedFromConversation.Enabled": removed_from_conversation_enabled, - "RemovedFromConversation.Template": removed_from_conversation_template, - "RemovedFromConversation.Sound": removed_from_conversation_sound, - "NewMessage.WithMedia.Enabled": new_message_with_media_enabled, - "NewMessage.WithMedia.Template": new_message_with_media_template, - } + 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, ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return NotificationInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - return NotificationInstance( + 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: """ @@ -393,6 +774,7 @@ def __repr__(self) -> str: class NotificationList(ListResource): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the NotificationList diff --git a/twilio/rest/conversations/v1/service/configuration/webhook.py b/twilio/rest/conversations/v1/service/configuration/webhook.py index 6152c44333..eee7e3f74e 100644 --- a/twilio/rest/conversations/v1/service/configuration/webhook.py +++ b/twilio/rest/conversations/v1/service/configuration/webhook.py @@ -12,9 +12,9 @@ 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 @@ -22,6 +22,7 @@ class WebhookInstance(InstanceResource): + class Method(object): GET = "GET" POST = "POST" @@ -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 @@ -146,6 +214,7 @@ def __repr__(self) -> str: class WebhookContext(InstanceContext): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the WebhookContext @@ -163,6 +232,22 @@ def __init__(self, version: Version, chat_service_sid: str): **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) -> WebhookInstance: """ Fetch the WebhookInstance @@ -170,17 +255,43 @@ def fetch(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], ) - return WebhookInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WebhookInstance: """ @@ -189,17 +300,59 @@ async def fetch_async(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], ) - return WebhookInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PreWebhookUrl": pre_webhook_url, + "PostWebhookUrl": post_webhook_url, + "Filters": serialize.map(filters, lambda e: e), + "Method": method, + } + ) + 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, @@ -218,6 +371,58 @@ def update( :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"] + ) + + 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 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 = 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( { "PreWebhookUrl": pre_webhook_url, @@ -226,15 +431,14 @@ def update( "Method": method, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WebhookInstance( - self._version, payload, chat_service_sid=self._solution["chat_service_sid"] + 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( @@ -254,24 +458,43 @@ async def update_async( :returns: The updated WebhookInstance """ - data = values.of( - { - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "Filters": serialize.map(filters, lambda e: e), - "Method": method, - } + payload, _, _ = await self._update_async( + pre_webhook_url=pre_webhook_url, + post_webhook_url=post_webhook_url, + filters=filters, + method=method, ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return WebhookInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - return WebhookInstance( + 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: """ @@ -284,6 +507,7 @@ def __repr__(self) -> str: class WebhookList(ListResource): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the WebhookList diff --git a/twilio/rest/conversations/v1/service/conversation/__init__.py b/twilio/rest/conversations/v1/service/conversation/__init__.py index e52a2bdb16..0dcfd00023 100644 --- a/twilio/rest/conversations/v1/service/conversation/__init__.py +++ b/twilio/rest/conversations/v1/service/conversation/__init__.py @@ -12,10 +12,10 @@ 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 @@ -29,10 +29,12 @@ class ConversationInstance(InstanceResource): + class State(object): INACTIVE = "inactive" ACTIVE = "active" CLOSED = "closed" + INITIALIZING = "initializing" class WebhookEnabledType(object): TRUE = "true" @@ -41,7 +43,7 @@ class WebhookEnabledType(object): """ :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. - :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/sms/services/api) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. :ivar sid: A 34 character string that uniquely identifies this resource. :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. :ivar 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. @@ -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[ @@ -171,6 +226,8 @@ def update( 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": """ Update the ConversationInstance @@ -180,11 +237,13 @@ def update( :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/sms/services/api) this conversation belongs to. + :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 """ @@ -199,6 +258,8 @@ def update( 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_async( @@ -215,6 +276,8 @@ async def update_async( 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 @@ -224,11 +287,13 @@ async def update_async( :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/sms/services/api) this conversation belongs to. + :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 """ @@ -243,6 +308,108 @@ async def update_async( timers_inactive=timers_inactive, timers_closed=timers_closed, unique_name=unique_name, + bindings_email_address=bindings_email_address, + 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 @@ -277,6 +444,7 @@ def __repr__(self) -> str: class ConversationContext(InstanceContext): + def __init__(self, version: Version, chat_service_sid: str, sid: str): """ Initialize the ConversationContext @@ -300,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[ @@ -313,13 +505,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -334,14 +563,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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: @@ -351,18 +609,45 @@ def fetch(self) -> ConversationInstance: :returns: The fetched ConversationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], ) - return ConversationInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ConversationInstance: """ @@ -371,20 +656,31 @@ async def fetch_async(self) -> ConversationInstance: :returns: The fetched ConversationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ConversationInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], ) - return ConversationInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -398,23 +694,16 @@ def update( timers_inactive: Union[str, object] = values.unset, timers_closed: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, - ) -> ConversationInstance: + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> tuple: """ - Update the ConversationInstance + Internal helper for update 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 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/sms/services/api) 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. - - :returns: The updated ConversationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -426,26 +715,30 @@ def update( "Timers.Inactive": timers_inactive, "Timers.Closed": timers_closed, "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return ConversationInstance( - self._version, - payload, - chat_service_sid=self._solution["chat_service_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -459,46 +752,212 @@ async def update_async( 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 + 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/sms/services/api) this conversation belongs to. + :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 """ - 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, - "UniqueName": unique_name, - } - ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + 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, + "UniqueName": unique_name, + "Bindings.Email.Address": bindings_email_address, + "Bindings.Email.Name": bindings_email_name, } ) + 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( + 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, @@ -506,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: """ @@ -556,12 +1072,14 @@ def __repr__(self) -> str: class ConversationPage(Page): + 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, chat_service_sid=self._solution["chat_service_sid"] ) @@ -576,25 +1094,241 @@ def __repr__(self) -> str: class ConversationList(ListResource): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the ConversationList - :param version: Version that contains the resource - :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/Conversations".format( + **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[ + "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: + """ + 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. + + :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( + { + "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" - """ - super().__init__(version) + headers["Accept"] = "application/json" - # Path Solution - self._solution = { - "chat_service_sid": chat_service_sid, - } - self._uri = "/Services/{chat_service_sid}/Conversations".format( - **self._solution + 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, x_twilio_webhook_enabled: Union[ "ConversationInstance.WebhookEnabledType", object @@ -608,50 +1342,46 @@ def create( 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: """ - Create the 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/sms/services/api) this conversation belongs to. + :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: The created ConversationInstance """ - 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, - } - ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - payload = self._version.create( - method="POST", uri=self._uri, data=data, headers=headers + 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 @@ -665,48 +1395,45 @@ async def create_async( state: Union["ConversationInstance.State", object] = values.unset, timers_inactive: Union[str, object] = values.unset, timers_closed: Union[str, object] = values.unset, - ) -> ConversationInstance: + bindings_email_address: Union[str, object] = values.unset, + bindings_email_name: Union[str, object] = values.unset, + ) -> 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. :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/sms/services/api) this conversation belongs to. + :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: 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, - } - ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - 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, @@ -722,8 +1449,8 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param str end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -758,8 +1485,8 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param str end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -780,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, @@ -793,8 +1590,8 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param str end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -805,6 +1602,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( start_date=start_date, @@ -828,8 +1626,8 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param str end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -840,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( @@ -851,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, @@ -864,8 +1731,8 @@ def page( Retrieve a single page of ConversationInstance records from the API. Request is executed immediately - :param start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -884,8 +1751,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ConversationPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -900,8 +1773,8 @@ async def page_async( Asynchronously retrieve a single page of ConversationInstance records from the API. Request is executed immediately - :param start_date: Start date in ISO8601 format for sorting and filtering list of Conversations. - :param end_date: End date in ISO8601 format for sorting and filtering list of Conversations. + :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 @@ -920,10 +1793,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ConversationPage(self._version, response, self._solution) + 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: """ @@ -935,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: """ @@ -947,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 e8a4dd4cfb..6c4e26231b 100644 --- a/twilio/rest/conversations/v1/service/conversation/message/__init__.py +++ b/twilio/rest/conversations/v1/service/conversation/message/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,6 +27,7 @@ class MessageInstance(InstanceResource): + class OrderType(object): ASC = "asc" DESC = "desc" @@ -51,7 +52,7 @@ class WebhookEnabledType(object): :ivar delivery: An object that contains the summary of delivery statuses for the message to non-chat participants. :ivar url: An absolute API resource URL for this message. :ivar links: Contains an absolute API resource URL to access the delivery & read receipts of this message. - :ivar content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content-api) template. + :ivar content_sid: The unique ID of the multi-channel [Rich Content](https://www.twilio.com/docs/content) template. """ def __init__( @@ -71,7 +72,7 @@ def __init__( self.index: Optional[int] = deserialize.integer(payload.get("index")) self.author: Optional[str] = payload.get("author") self.body: Optional[str] = payload.get("body") - self.media: Optional[List[object]] = payload.get("media") + self.media: Optional[List[Dict[str, object]]] = payload.get("media") self.attributes: Optional[str] = payload.get("attributes") self.participant_sid: Optional[str] = payload.get("participant_sid") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( @@ -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[ @@ -171,6 +225,7 @@ def update( 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": """ Update the MessageInstance @@ -181,6 +236,7 @@ def update( :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. :returns: The updated MessageInstance """ @@ -191,6 +247,7 @@ def update( date_created=date_created, date_updated=date_updated, attributes=attributes, + subject=subject, ) async def update_async( @@ -203,6 +260,7 @@ async def update_async( 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 @@ -213,6 +271,7 @@ async def update_async( :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. :returns: The updated MessageInstance """ @@ -223,6 +282,77 @@ async def update_async( date_created=date_created, date_updated=date_updated, attributes=attributes, + 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. + :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. + + :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. + :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. + + :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 @@ -243,6 +373,7 @@ def __repr__(self) -> str: class MessageContext(InstanceContext): + def __init__( self, version: Version, chat_service_sid: str, conversation_sid: str, sid: str ): @@ -268,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[ @@ -281,13 +436,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -302,14 +494,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> MessageInstance: @@ -319,19 +540,47 @@ def fetch(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MessageInstance: """ @@ -340,21 +589,33 @@ async def fetch_async(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MessageInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -364,19 +625,15 @@ def update( date_created: Union[datetime, object] = values.unset, date_updated: Union[datetime, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> MessageInstance: + subject: Union[str, object] = values.unset, + ) -> 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. + Internal helper for update operation - :returns: The updated MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Author": author, @@ -384,27 +641,29 @@ def update( "DateCreated": serialize.iso8601_datetime(date_created), "DateUpdated": serialize.iso8601_datetime(date_updated), "Attributes": attributes, + "Subject": subject, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return MessageInstance( - self._version, - payload, - chat_service_sid=self._solution["chat_service_sid"], - conversation_sid=self._solution["conversation_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -414,9 +673,10 @@ async def update_async( 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 + 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`. @@ -424,28 +684,19 @@ async def update_async( :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. :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, - } - ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - - 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, @@ -454,13 +705,189 @@ 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: """ - if self._delivery_receipts is None: - self._delivery_receipts = DeliveryReceiptList( + 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. + :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. + + :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. + :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. + + :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. + :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. + + :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"], @@ -479,12 +906,14 @@ def __repr__(self) -> str: 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, @@ -502,6 +931,7 @@ def __repr__(self) -> str: class MessageList(ListResource): + def __init__(self, version: Version, chat_service_sid: str, conversation_sid: str): """ Initialize the MessageList @@ -522,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 @@ -535,22 +965,15 @@ def create( media_sid: Union[str, object] = values.unset, content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, - ) -> MessageInstance: + subject: Union[str, object] = values.unset, + ) -> 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-api) 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. + Internal helper for create operation - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Author": author, @@ -561,17 +984,67 @@ def create( "MediaSid": media_sid, "ContentSid": content_sid, "ContentVariables": content_variables, + "Subject": subject, } ) headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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[ + "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. + :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 + """ + 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, @@ -579,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 @@ -592,9 +1065,10 @@ async def create_async( media_sid: Union[str, object] = values.unset, content_sid: Union[str, object] = values.unset, content_variables: Union[str, object] = values.unset, - ) -> MessageInstance: + subject: Union[str, object] = values.unset, + ) -> 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`. @@ -603,11 +1077,54 @@ async def create_async( :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-api) template, required for template-generated messages. **Note** that if this field is set, `Body` and `MediaSid` parameters are ignored. + :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( { "Author": author, @@ -618,17 +1135,67 @@ async def create_async( "MediaSid": media_sid, "ContentSid": content_sid, "ContentVariables": content_variables, + "Subject": subject, } ) headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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. + :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 + """ + 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, @@ -636,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. + :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: 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, @@ -690,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, @@ -711,6 +1385,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -740,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( @@ -749,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, @@ -776,8 +1508,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MessagePage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -806,10 +1544,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MessagePage(self._version, response, self._solution) + 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: """ @@ -821,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: """ @@ -833,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 01e6f392f2..d729edcd52 100644 --- a/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py +++ b/twilio/rest/conversations/v1/service/conversation/message/delivery_receipt.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class DeliveryReceiptInstance(InstanceResource): + class DeliveryStatus(object): READ = "read" FAILED = "failed" @@ -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 @@ -131,6 +151,7 @@ def __repr__(self) -> str: class DeliveryReceiptContext(InstanceContext): + def __init__( self, version: Version, @@ -161,6 +182,22 @@ def __init__( **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) -> DeliveryReceiptInstance: """ Fetch the DeliveryReceiptInstance @@ -168,13 +205,25 @@ def fetch(self) -> DeliveryReceiptInstance: :returns: The fetched DeliveryReceiptInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return 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 DeliveryReceiptInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeliveryReceiptInstance and return response metadata + + + :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"], @@ -182,6 +231,23 @@ def fetch(self) -> DeliveryReceiptInstance: 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> DeliveryReceiptInstance: """ @@ -190,13 +256,25 @@ async def fetch_async(self) -> DeliveryReceiptInstance: :returns: The fetched DeliveryReceiptInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return 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 DeliveryReceiptInstance( + 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"], @@ -204,6 +282,7 @@ async def fetch_async(self) -> DeliveryReceiptInstance: message_sid=self._solution["message_sid"], sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -216,12 +295,14 @@ def __repr__(self) -> str: class DeliveryReceiptPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> DeliveryReceiptInstance: """ Build an instance of DeliveryReceiptInstance :param payload: Payload response from the API """ + return DeliveryReceiptInstance( self._version, payload, @@ -240,6 +321,7 @@ def __repr__(self) -> str: class DeliveryReceiptList(ListResource): + def __init__( self, version: Version, @@ -318,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, @@ -337,6 +469,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -363,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( @@ -371,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, @@ -395,8 +579,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DeliveryReceiptPage(self._version, response, self._solution) + 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 DeliveryReceiptPage(self._version, response, solution=self._solution) async def page_async( self, @@ -422,10 +612,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return DeliveryReceiptPage(self._version, response, self._solution) + 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: """ @@ -437,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: """ @@ -449,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 dbec40f549..960f36fd16 100644 --- a/twilio/rest/conversations/v1/service/conversation/participant.py +++ b/twilio/rest/conversations/v1/service/conversation/participant.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class ParticipantInstance(InstanceResource): + class WebhookEnabledType(object): TRUE = "true" FALSE = "false" @@ -33,12 +34,12 @@ class WebhookEnabledType(object): :ivar chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Participant resource is associated with. :ivar conversation_sid: The unique ID of the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for this participant. :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar 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 to communicate. Limited to 256 characters. - :ivar 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. + :ivar 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. + :ivar 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. :ivar messaging_binding: Information about how this participant exchanges messages with the conversation. A JSON parameter consisting of type and address fields of the participant. :ivar role_sid: The SID of a conversation-level [Role](https://www.twilio.com/docs/conversations/api/role-resource) to assign to the participant. - :ivar date_created: The date that this resource was created. - :ivar date_updated: The date that this resource was last updated. + :ivar date_created: The date on which this resource was created. + :ivar date_updated: The date on which this resource was last updated. :ivar url: An absolute API resource URL for this participant. :ivar last_read_message_index: Index of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. :ivar last_read_timestamp: Timestamp of last “read” message in the [Conversation](https://www.twilio.com/docs/conversations/api/conversation-resource) for the Participant. @@ -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[ @@ -171,10 +225,10 @@ def update( 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 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 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 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. @@ -215,10 +269,10 @@ async def update_async( 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 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 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 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. @@ -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 @@ -251,6 +393,7 @@ def __repr__(self) -> str: class ParticipantContext(InstanceContext): + def __init__( self, version: Version, chat_service_sid: str, conversation_sid: str, sid: str ): @@ -274,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[ @@ -287,13 +454,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -308,14 +512,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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: @@ -325,19 +558,47 @@ def fetch(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return ParticipantInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ParticipantInstance: """ @@ -346,21 +607,33 @@ async def fetch_async(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return ParticipantInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -374,23 +647,14 @@ 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 that this resource was created. - :param date_updated: The date that 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 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( { "DateCreated": serialize.iso8601_datetime(date_created), @@ -404,25 +668,26 @@ def update( "LastReadTimestamp": last_read_timestamp, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return ParticipantInstance( - self._version, - payload, - chat_service_sid=self._solution["chat_service_sid"], - conversation_sid=self._solution["conversation_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ParticipantInstance.WebhookEnabledType", object @@ -438,13 +703,13 @@ 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. - :param date_updated: The date that 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 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 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. @@ -453,29 +718,175 @@ async def update_async( :returns: The updated ParticipantInstance """ - data = values.of( - { - "DateCreated": serialize.iso8601_datetime(date_created), - "DateUpdated": serialize.iso8601_datetime(date_updated), - "Identity": identity, - "Attributes": attributes, - "RoleSid": role_sid, - "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, - "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, - "LastReadMessageIndex": last_read_message_index, - "LastReadTimestamp": last_read_timestamp, - } + 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, ) - headers = values.of( + return ParticipantInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + 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( { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "DateCreated": serialize.iso8601_datetime(date_created), + "DateUpdated": serialize.iso8601_datetime(date_updated), + "Identity": identity, + "Attributes": attributes, + "RoleSid": role_sid, + "MessagingBinding.ProxyAddress": messaging_binding_proxy_address, + "MessagingBinding.ProjectedAddress": messaging_binding_projected_address, + "LastReadMessageIndex": last_read_message_index, + "LastReadTimestamp": last_read_timestamp, } ) + 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" - payload = await self._version.update_async( + 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[ + "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, @@ -484,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 @@ -495,12 +958,14 @@ def __repr__(self) -> str: class ParticipantPage(Page): + 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, @@ -518,6 +983,7 @@ def __repr__(self) -> str: class ParticipantList(ListResource): + def __init__(self, version: Version, chat_service_sid: str, conversation_sid: str): """ Initialize the ParticipantList @@ -538,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 @@ -551,22 +1017,14 @@ 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 Conversation 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( { "Identity": identity, @@ -582,12 +1040,58 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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[ + "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, @@ -595,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 @@ -608,22 +1112,62 @@ 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 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 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: 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( { "Identity": identity, @@ -639,12 +1183,58 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -652,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, @@ -702,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, @@ -721,6 +1409,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -747,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( @@ -755,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, @@ -779,8 +1519,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ParticipantPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -806,10 +1552,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ParticipantPage(self._version, response, self._solution) + 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: """ @@ -821,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: """ @@ -833,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 88e848f351..d95e4d364e 100644 --- a/twilio/rest/conversations/v1/service/conversation/webhook.py +++ b/twilio/rest/conversations/v1/service/conversation/webhook.py @@ -12,10 +12,10 @@ 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 @@ -24,9 +24,10 @@ 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 @@ -194,6 +286,7 @@ def __repr__(self) -> str: class WebhookContext(InstanceContext): + def __init__( self, version: Version, chat_service_sid: str, conversation_sid: str, sid: str ): @@ -217,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 @@ -224,9 +331,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -236,9 +365,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance 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) -> WebhookInstance: @@ -248,19 +401,47 @@ def fetch(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WebhookInstance: """ @@ -269,39 +450,47 @@ async def fetch_async(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + 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( + 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( { "Configuration.Url": configuration_url, @@ -315,13 +504,42 @@ def update( "Configuration.FlowSid": configuration_flow_sid, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -330,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: @@ -347,8 +565,39 @@ 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( { "Configuration.Url": configuration_url, @@ -362,13 +611,42 @@ async def update_async( "Configuration.FlowSid": configuration_flow_sid, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -377,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 @@ -388,12 +701,14 @@ def __repr__(self) -> str: class WebhookPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: """ Build an instance of WebhookInstance :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, @@ -411,6 +726,7 @@ def __repr__(self) -> str: class WebhookList(ListResource): + def __init__(self, version: Version, chat_service_sid: str, conversation_sid: str): """ Initialize the WebhookList @@ -431,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, @@ -440,20 +756,14 @@ 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( { "Target": target, @@ -469,13 +779,48 @@ def create( "Configuration.ReplayAfter": configuration_replay_after, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -483,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, @@ -492,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. @@ -504,8 +849,42 @@ 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( { "Target": target, @@ -521,13 +900,48 @@ async def create_async( "Configuration.ReplayAfter": configuration_replay_after, } ) + 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, + 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, @@ -535,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, @@ -585,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, @@ -604,6 +1108,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -630,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( @@ -638,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, @@ -662,8 +1218,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return WebhookPage(self._version, response, self._solution) + 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 WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -689,10 +1251,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return WebhookPage(self._version, response, self._solution) + 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: """ @@ -704,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: """ @@ -716,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 new file mode 100644 index 0000000000..b6305a6aae --- /dev/null +++ b/twilio/rest/conversations/v1/service/conversation_with_participants.py @@ -0,0 +1,474 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Conversations + 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 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 ConversationWithParticipantsInstance(InstanceResource): + + class State(object): + INITIALIZING = "initializing" + INACTIVE = "inactive" + ACTIVE = "active" + CLOSED = "closed" + + class WebhookEnabledType(object): + TRUE = "true" + FALSE = "false" + + """ + :ivar account_sid: The unique ID of the [Account](https://www.twilio.com/docs/iam/api/account) responsible for this conversation. + :ivar chat_service_sid: The unique ID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) this conversation belongs to. + :ivar messaging_service_sid: The unique ID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) this conversation belongs to. + :ivar sid: A 34 character string that uniquely identifies this resource. + :ivar friendly_name: The human-readable name of this conversation, limited to 256 characters. Optional. + :ivar 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. + :ivar 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. + :ivar state: + :ivar date_created: The date that this resource was created. + :ivar date_updated: The date that this resource was last updated. + :ivar timers: Timer date values representing state update for this conversation. + :ivar links: Contains absolute URLs to access the [participants](https://www.twilio.com/docs/conversations/api/conversation-participant-resource), [messages](https://www.twilio.com/docs/conversations/api/conversation-message-resource) and [webhooks](https://www.twilio.com/docs/conversations/api/conversation-scoped-webhook-resource) of this conversation. + :ivar bindings: + :ivar url: An absolute API resource URL for this conversation. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], chat_service_sid: str + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.chat_service_sid: Optional[str] = payload.get("chat_service_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.attributes: Optional[str] = payload.get("attributes") + self.state: Optional["ConversationWithParticipantsInstance.State"] = ( + payload.get("state") + ) + 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.timers: Optional[Dict[str, object]] = payload.get("timers") + self.links: Optional[Dict[str, object]] = payload.get("links") + self.bindings: Optional[Dict[str, object]] = payload.get("bindings") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "chat_service_sid": chat_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 ( + "".format( + context + ) + ) + + +class ConversationWithParticipantsList(ListResource): + + def __init__(self, version: Version, chat_service_sid: str): + """ + Initialize the ConversationWithParticipantsList + + :param version: Version that contains the resource + :param chat_service_sid: The SID of the [Conversation Service](https://www.twilio.com/docs/conversations/api/service-resource) the Conversation resource is associated with. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "chat_service_sid": chat_service_sid, + } + self._uri = "/Services/{chat_service_sid}/ConversationWithParticipants".format( + **self._solution + ) + + 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, + ) -> 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, + "Participant": serialize.map(participant, lambda e: e), + } + ) + 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[ + "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"] + ) + + 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, 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( + { + "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, + "Participant": serialize.map(participant, lambda e: e), + } + ) + 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 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/conversations/v1/service/participant_conversation.py b/twilio/rest/conversations/v1/service/participant_conversation.py index b4de04f277..790e753f20 100644 --- a/twilio/rest/conversations/v1/service/participant_conversation.py +++ b/twilio/rest/conversations/v1/service/participant_conversation.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +24,7 @@ class ParticipantConversationInstance(InstanceResource): + class State(object): INACTIVE = "inactive" ACTIVE = "active" @@ -71,18 +72,18 @@ def __init__( self.conversation_attributes: Optional[str] = payload.get( "conversation_attributes" ) - self.conversation_date_created: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("conversation_date_created")) - self.conversation_date_updated: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("conversation_date_updated")) + self.conversation_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_created")) + ) + self.conversation_date_updated: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("conversation_date_updated")) + ) self.conversation_created_by: Optional[str] = payload.get( "conversation_created_by" ) - self.conversation_state: Optional[ - "ParticipantConversationInstance.State" - ] = payload.get("conversation_state") + self.conversation_state: Optional["ParticipantConversationInstance.State"] = ( + payload.get("conversation_state") + ) self.conversation_timers: Optional[Dict[str, object]] = payload.get( "conversation_timers" ) @@ -105,12 +106,14 @@ def __repr__(self) -> str: class ParticipantConversationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ParticipantConversationInstance: """ Build an instance of ParticipantConversationInstance :param payload: Payload response from the API """ + return ParticipantConversationInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -125,6 +128,7 @@ def __repr__(self) -> str: class ParticipantConversationList(ListResource): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the ParticipantConversationList @@ -205,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, @@ -228,6 +292,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -260,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( @@ -270,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, @@ -300,8 +428,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ParticipantConversationPage(self._version, response, self._solution) + 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 ParticipantConversationPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -333,10 +469,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 ParticipantConversationPage(self._version, response, self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> ParticipantConversationPage: """ @@ -348,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: """ @@ -360,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 2ae2c16fb1..f7373513a0 100644 --- a/twilio/rest/conversations/v1/service/role.py +++ b/twilio/rest/conversations/v1/service/role.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class RoleInstance(InstanceResource): + class RoleType(object): CONVERSATION = "conversation" SERVICE = "service" @@ -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 @@ -156,6 +218,7 @@ def __repr__(self) -> str: class RoleContext(InstanceContext): + def __init__(self, version: Version, chat_service_sid: str, sid: str): """ Initialize the RoleContext @@ -173,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 @@ -180,9 +257,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -192,9 +291,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance 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) -> RoleInstance: @@ -204,18 +327,45 @@ def fetch(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], ) - return RoleInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RoleInstance: """ @@ -224,12 +374,7 @@ async def fetch_async(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -237,26 +382,54 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -264,26 +437,55 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -291,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 @@ -302,12 +521,14 @@ def __repr__(self) -> str: class RolePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: """ Build an instance of RoleInstance :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) @@ -322,6 +543,7 @@ def __repr__(self) -> str: class RoleList(ListResource): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the RoleList @@ -338,6 +560,33 @@ def __init__(self, version: Version, chat_service_sid: str): } self._uri = "/Services/{chat_service_sid}/Roles".format(**self._solution) + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: 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.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: @@ -350,6 +599,43 @@ def create( :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"] + ) + + 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, 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( { "FriendlyName": friendly_name, @@ -357,15 +643,14 @@ def create( "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RoleInstance( - self._version, payload, chat_service_sid=self._solution["chat_service_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( @@ -380,23 +665,32 @@ async def create_async( :returns: The created RoleInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Permission": serialize.map(permission, lambda e: e), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return RoleInstance( + self._version, payload, chat_service_sid=self._solution["chat_service_sid"] ) - return RoleInstance( + 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, @@ -448,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, @@ -467,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -493,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( @@ -501,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, @@ -525,8 +921,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RolePage(self._version, response, self._solution) + 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 RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -552,10 +954,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RolePage(self._version, response, self._solution) + 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: """ @@ -567,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: """ @@ -579,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 10747179bf..55e16cd848 100644 --- a/twilio/rest/conversations/v1/service/user/__init__.py +++ b/twilio/rest/conversations/v1/service/user/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,6 +27,7 @@ class UserInstance(InstanceResource): + class WebhookEnabledType(object): TRUE = "true" FALSE = "false" @@ -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: """ @@ -218,6 +324,7 @@ def __repr__(self) -> str: class UserContext(InstanceContext): + def __init__(self, version: Version, chat_service_sid: str, sid: str): """ Initialize the UserContext @@ -237,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[ @@ -250,13 +381,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -271,14 +439,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> UserInstance: @@ -288,18 +485,45 @@ def fetch(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserInstance: """ @@ -308,20 +532,31 @@ async def fetch_async(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + chat_service_sid=self._solution["chat_service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -329,17 +564,14 @@ 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( { "FriendlyName": friendly_name, @@ -347,16 +579,50 @@ def update( "RoleSid": role_sid, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + 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 - payload = self._version.update( + 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, + 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, @@ -364,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 @@ -372,17 +638,47 @@ 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( { "FriendlyName": friendly_name, @@ -390,23 +686,90 @@ async def update_async( "RoleSid": role_sid, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return UserInstance( - self._version, - payload, - chat_service_sid=self._solution["chat_service_sid"], - sid=self._solution["sid"], + 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[ + "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, + chat_service_sid=self._solution["chat_service_sid"], + 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, + 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: """ @@ -431,12 +794,14 @@ def __repr__(self) -> str: 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, chat_service_sid=self._solution["chat_service_sid"] ) @@ -451,6 +816,7 @@ def __repr__(self) -> str: class UserList(ListResource): + def __init__(self, version: Version, chat_service_sid: str): """ Initialize the UserList @@ -467,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[ @@ -476,18 +842,14 @@ 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 + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Identity": identity, @@ -499,17 +861,51 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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, + 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[ @@ -518,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 @@ -528,8 +924,37 @@ 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( { "Identity": identity, @@ -541,16 +966,83 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -601,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, @@ -620,6 +1162,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -646,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( @@ -654,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, @@ -678,8 +1272,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserPage(self._version, response, self._solution) + 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 UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -705,10 +1305,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserPage(self._version, response, self._solution) + 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: """ @@ -720,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: """ @@ -732,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 40e02f746a..7a05c5fc73 100644 --- a/twilio/rest/conversations/v1/service/user/user_conversation.py +++ b/twilio/rest/conversations/v1/service/user/user_conversation.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class UserConversationInstance(InstanceResource): + class NotificationLevel(object): DEFAULT = "default" MUTED = "muted" @@ -76,9 +77,9 @@ def __init__( self.participant_sid: Optional[str] = payload.get("participant_sid") self.user_sid: Optional[str] = payload.get("user_sid") self.friendly_name: Optional[str] = payload.get("friendly_name") - self.conversation_state: Optional[ - "UserConversationInstance.State" - ] = payload.get("conversation_state") + self.conversation_state: Optional["UserConversationInstance.State"] = ( + payload.get("conversation_state") + ) self.timers: Optional[Dict[str, object]] = payload.get("timers") self.attributes: Optional[str] = payload.get("attributes") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( @@ -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 @@ -212,6 +296,7 @@ def __repr__(self) -> str: class UserConversationContext(InstanceContext): + def __init__( self, version: Version, @@ -239,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 @@ -246,9 +345,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -258,9 +379,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance 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) -> UserConversationInstance: @@ -270,19 +415,47 @@ def fetch(self) -> UserConversationInstance: :returns: The fetched UserConversationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return 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 UserConversationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserConversationInstance: """ @@ -291,37 +464,47 @@ async def fetch_async(self) -> UserConversationInstance: :returns: The fetched UserConversationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return 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 UserConversationInstance( + 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( + 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( { "NotificationLevel": notification_level, @@ -329,13 +512,38 @@ def update( "LastReadMessageIndex": last_read_message_index, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -344,23 +552,52 @@ 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( { "NotificationLevel": notification_level, @@ -368,13 +605,38 @@ async def update_async( "LastReadMessageIndex": last_read_message_index, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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 +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 @@ -394,12 +687,14 @@ def __repr__(self) -> str: class UserConversationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: """ Build an instance of UserConversationInstance :param payload: Payload response from the API """ + return UserConversationInstance( self._version, payload, @@ -417,6 +712,7 @@ def __repr__(self) -> str: class UserConversationList(ListResource): + def __init__(self, version: Version, chat_service_sid: str, user_sid: str): """ Initialize the UserConversationList @@ -489,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, @@ -508,6 +854,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -534,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( @@ -542,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, @@ -566,8 +964,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserConversationPage(self._version, response, self._solution) + 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 UserConversationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -593,10 +997,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserConversationPage(self._version, response, self._solution) + 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: """ @@ -608,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: """ @@ -620,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 72a285885e..b149577147 100644 --- a/twilio/rest/conversations/v1/user/__init__.py +++ b/twilio/rest/conversations/v1/user/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,6 +25,7 @@ class UserInstance(InstanceResource): + class WebhookEnabledType(object): TRUE = "true" FALSE = "false" @@ -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: """ @@ -210,6 +316,7 @@ def __repr__(self) -> str: class UserContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the UserContext @@ -227,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[ @@ -240,13 +371,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -261,14 +429,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> UserInstance: @@ -278,17 +475,43 @@ def fetch(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return UserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserInstance: """ @@ -297,19 +520,29 @@ async def fetch_async(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return UserInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -317,17 +550,14 @@ 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( { "FriendlyName": friendly_name, @@ -335,19 +565,26 @@ def update( "RoleSid": role_sid, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( + 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 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 @@ -357,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. @@ -366,6 +603,58 @@ 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( { "FriendlyName": friendly_name, @@ -373,22 +662,84 @@ async def update_async( "RoleSid": role_sid, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + 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 - payload = await self._version.update_async( + 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 ) - return UserInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def user_conversations(self) -> UserConversationList: + 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: """ - Access the user_conversations + 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: + """ + Access the user_conversations """ if self._user_conversations is None: self._user_conversations = UserConversationList( @@ -408,12 +759,14 @@ def __repr__(self) -> str: 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) def __repr__(self) -> str: @@ -426,6 +779,7 @@ def __repr__(self) -> str: class UserList(ListResource): + def __init__(self, version: Version): """ Initialize the UserList @@ -437,7 +791,7 @@ def __init__(self, version: Version): self._uri = "/Users" - def create( + def _create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -446,18 +800,14 @@ 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 + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Identity": identity, @@ -469,15 +819,19 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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 ) - return UserInstance(self._version, payload) - - async def create_async( + def create( self, identity: str, x_twilio_webhook_enabled: Union[ @@ -488,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 @@ -498,6 +852,63 @@ 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( { "Identity": identity, @@ -509,14 +920,79 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -567,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, @@ -586,6 +1112,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -612,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( @@ -620,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, @@ -644,7 +1222,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 UserPage(self._version, response) async def page_async( @@ -671,11 +1255,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 4134066afd..c6dd85ac39 100644 --- a/twilio/rest/conversations/v1/user/user_conversation.py +++ b/twilio/rest/conversations/v1/user/user_conversation.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class UserConversationInstance(InstanceResource): + class NotificationLevel(object): DEFAULT = "default" MUTED = "muted" @@ -75,9 +76,9 @@ def __init__( self.participant_sid: Optional[str] = payload.get("participant_sid") self.user_sid: Optional[str] = payload.get("user_sid") self.friendly_name: Optional[str] = payload.get("friendly_name") - self.conversation_state: Optional[ - "UserConversationInstance.State" - ] = payload.get("conversation_state") + self.conversation_state: Optional["UserConversationInstance.State"] = ( + payload.get("conversation_state") + ) self.timers: Optional[Dict[str, object]] = payload.get("timers") self.attributes: Optional[str] = payload.get("attributes") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( @@ -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 @@ -209,6 +293,7 @@ def __repr__(self) -> str: class UserConversationContext(InstanceContext): + def __init__(self, version: Version, user_sid: str, conversation_sid: str): """ Initialize the UserConversationContext @@ -228,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 @@ -235,9 +334,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -247,9 +368,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserConversationInstance 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) -> UserConversationInstance: @@ -259,18 +404,45 @@ def fetch(self) -> UserConversationInstance: :returns: The fetched UserConversationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], ) - return UserConversationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserConversationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserConversationInstance: """ @@ -279,36 +451,45 @@ async def fetch_async(self) -> UserConversationInstance: :returns: The fetched UserConversationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserConversationInstance( + self._version, + payload, + user_sid=self._solution["user_sid"], + conversation_sid=self._solution["conversation_sid"], ) - return UserConversationInstance( + 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( + 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( { "NotificationLevel": notification_level, @@ -316,13 +497,38 @@ def update( "LastReadMessageIndex": last_read_message_index, } ) + 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, + 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, @@ -330,23 +536,51 @@ 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( { "NotificationLevel": notification_level, @@ -354,13 +588,38 @@ async def update_async( "LastReadMessageIndex": last_read_message_index, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -368,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 @@ -379,12 +668,14 @@ def __repr__(self) -> str: class UserConversationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UserConversationInstance: """ Build an instance of UserConversationInstance :param payload: Payload response from the API """ + return UserConversationInstance( self._version, payload, user_sid=self._solution["user_sid"] ) @@ -399,6 +690,7 @@ def __repr__(self) -> str: class UserConversationList(ListResource): + def __init__(self, version: Version, user_sid: str): """ Initialize the UserConversationList @@ -465,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, @@ -484,6 +826,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -510,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( @@ -518,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, @@ -542,8 +936,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserConversationPage(self._version, response, self._solution) + 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 UserConversationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -569,10 +969,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserConversationPage(self._version, response, self._solution) + 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: """ @@ -584,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: """ @@ -596,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..fd904a0c7b --- /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_sid: str, communication_id: str = None): + """ + Access the CommunicationList resource + + :param conversation_sid: + + :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_sid) + 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_sid: str, participant_id: str = None): + """ + Access the ParticipantList resource + + :param conversation_sid: + + :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_sid) + 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..b2a656f35a --- /dev/null +++ b/twilio/rest/conversations/v2/action.py @@ -0,0 +1,512 @@ +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): + """ + :ivar id: Unique identifier for this Action. + :ivar type: The type of action. Accepted values: SEND_MESSAGE. + :ivar status: Current status of the Action. - PENDING: Action accepted, awaiting downstream confirmation - COMPLETED: Downstream backend confirmed the action - FAILED: Downstream backend reported a failure + :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: Channel type for address resolution. + """ + + 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.str"] = 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..c8875a2756 --- /dev/null +++ b/twilio/rest/conversations/v2/communication.py @@ -0,0 +1,1037 @@ +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): + """ + :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_sid: str, + sid: 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_sid is not None or sid is not None: + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + + 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_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + 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_sid: str, sid: str): + """ + Initialize the CommunicationContext + + :param version: Version that contains the resource + :param conversation_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Communications/{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) -> CommunicationInstance: + """ + Fetch the CommunicationInstance + + + :returns: The fetched CommunicationInstance + """ + payload, _, _ = self._fetch() + return CommunicationInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + 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_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" + + 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_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + 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_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 + + :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_sid=self._solution["conversation_sid"] + ) + + 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: + """ + + 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.CreateCommunicationInConversationRequestAuthor] + ] = payload.get("recipients") + + 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 + ), + } + + class CreateCommunicationInConversationRequestAuthor(object): + """ + :ivar address: + :ivar channel: + :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 + ), + } + + def __init__(self, version: Version, conversation_sid: str): + """ + Initialize the CommunicationList + + :param version: Version that contains the resource + :param conversation_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/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_sid=self._solution["conversation_sid"] + ) + + 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_sid=self._solution["conversation_sid"] + ) + 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_sid=self._solution["conversation_sid"] + ) + + 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_sid=self._solution["conversation_sid"] + ) + 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, sid: str) -> CommunicationContext: + """ + Constructs a CommunicationContext + + :param sid: + """ + return CommunicationContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> CommunicationContext: + """ + Constructs a CommunicationContext + + :param sid: + """ + return CommunicationContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + 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..f2939d1359 --- /dev/null +++ b/twilio/rest/conversations/v2/configuration.py @@ -0,0 +1,1655 @@ +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): + """ + :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: 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: 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. + :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, sid: Optional[str] = None + ): + super().__init__(version) + + 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.str"] = ( + 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") + 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 sid is not None: + self._solution = { + "sid": sid, + } + + 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, + sid=self._solution["sid"], + ) + 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, sid: str): + """ + Initialize the ConfigurationContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ControlPlane/Configurations/{sid}".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, + sid=self._solution["sid"], + ) + + 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, + 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) -> ConfigurationInstance: + """ + Asynchronous coroutine to fetch the ConfigurationInstance + + + :returns: The fetched ConfigurationInstance + """ + payload, _, _ = await self._fetch_async() + return ConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + 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, + sid=self._solution["sid"], + ) + 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, sid=self._solution["sid"]) + + 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, sid=self._solution["sid"] + ) + 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, sid=self._solution["sid"]) + + 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, 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 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: The strategy Conversation Orchestrator uses to assign communications to conversations. + :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. + """ + + 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" + ) + + 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, + } + + 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 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: The strategy Conversation Orchestrator uses to assign communications to conversations. + :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. + """ + + 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" + ) + + 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, + } + + 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, sid: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param sid: + """ + return ConfigurationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConfigurationContext: + """ + Constructs a ConfigurationContext + + :param sid: + """ + return ConfigurationContext(self._version, sid=sid) + + 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..62a48c115b --- /dev/null +++ b/twilio/rest/conversations/v2/conversation.py @@ -0,0 +1,1613 @@ +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): + """ + :ivar id: Conversation ID. + :ivar account_id: Account ID. + :ivar configuration_id: Configuration ID. + :ivar status: Conversation 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, sid: 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 sid is not None: + self._solution = { + "sid": sid, + } + + 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, + sid=self._solution["sid"], + ) + 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, sid: str): + """ + Initialize the ConversationContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Conversations/{sid}".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, + sid=self._solution["sid"], + ) + + 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, + 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) -> 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"], + ) + + 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 _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, sid=self._solution["sid"]) + + 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, sid=self._solution["sid"] + ) + 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, sid=self._solution["sid"]) + + 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, sid=self._solution["sid"] + ) + 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, sid=self._solution["sid"]) + + 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, sid=self._solution["sid"] + ) + 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, sid=self._solution["sid"]) + + 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, 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 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: The channel for Communication. + :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[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 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: + :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: The state of the 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: The state of the 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, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: + """ + return ConversationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ConversationContext: + """ + Constructs a ConversationContext + + :param sid: + """ + return ConversationContext(self._version, sid=sid) + + 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..b7e62cfa27 --- /dev/null +++ b/twilio/rest/conversations/v2/operation.py @@ -0,0 +1,274 @@ +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): + """ + :ivar operation_id: Unique identifier for the long-running operation. + :ivar status: Current status of the operation. + :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], sid: 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 sid is not None: + self._solution = { + "sid": sid, + } + + 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, + sid=self._solution["sid"], + ) + 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, sid: str): + """ + Initialize the OperationContext + + :param version: Version that contains the resource + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/ControlPlane/Operations/{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) -> OperationInstance: + """ + Fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = self._fetch() + return OperationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + 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, + 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) -> OperationInstance: + """ + Asynchronous coroutine to fetch the OperationInstance + + + :returns: The fetched OperationInstance + """ + payload, _, _ = await self._fetch_async() + return OperationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + 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, + 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 OperationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> OperationContext: + """ + Constructs a OperationContext + + :param sid: + """ + return OperationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OperationContext: + """ + Constructs a OperationContext + + :param sid: + """ + return OperationContext(self._version, sid=sid) + + 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..e752af8c91 --- /dev/null +++ b/twilio/rest/conversations/v2/participant.py @@ -0,0 +1,1137 @@ +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): + """ + :ivar id: Participant ID. + :ivar conversation_id: Conversation ID. + :ivar account_id: Account ID. + :ivar name: Participant display name. + :ivar type: Type of Participant in the Conversation. + :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_sid: str, + sid: 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_sid is not None or sid is not None: + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + + 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_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + 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_sid: str, sid: str): + """ + Initialize the ParticipantContext + + :param version: Version that contains the resource + :param conversation_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + "sid": sid, + } + self._uri = "/Conversations/{conversation_sid}/Participants/{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) -> ParticipantInstance: + """ + Fetch the ParticipantInstance + + + :returns: The fetched ParticipantInstance + """ + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + 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_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" + + 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_sid=self._solution["conversation_sid"], + 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, + conversation_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + 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_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + 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_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + 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_sid=self._solution["conversation_sid"], + sid=self._solution["sid"], + ) + + 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_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 + + :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_sid=self._solution["conversation_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ParticipantList(ListResource): + + class CreateParticipantInConversationRequest(object): + """ + :ivar name: + :ivar type: + :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.CreateParticipantInConversationRequestAddresses] + ] = 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 CreateParticipantInConversationRequestAddresses(object): + """ + :ivar channel: + :ivar address: + :ivar channel_id: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.channel: Optional["ParticipantInstance.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 UpdateParticipantInConversationRequest(object): + """ + :ivar name: + :ivar type: + :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.CreateParticipantInConversationRequestAddresses] + ] = 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_sid: str): + """ + Initialize the ParticipantList + + :param version: Version that contains the resource + :param conversation_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "conversation_sid": conversation_sid, + } + self._uri = "/Conversations/{conversation_sid}/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_sid=self._solution["conversation_sid"] + ) + + 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_sid=self._solution["conversation_sid"] + ) + 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_sid=self._solution["conversation_sid"] + ) + + 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_sid=self._solution["conversation_sid"] + ) + 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, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __call__(self, sid: str) -> ParticipantContext: + """ + Constructs a ParticipantContext + + :param sid: + """ + return ParticipantContext( + self._version, conversation_sid=self._solution["conversation_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/events/EventsBase.py b/twilio/rest/events/EventsBase.py index 17c087a1d5..eb2251ae4e 100644 --- a/twilio/rest/events/EventsBase.py +++ b/twilio/rest/events/EventsBase.py @@ -17,6 +17,7 @@ class EventsBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Events Domain diff --git a/twilio/rest/events/v1/__init__.py b/twilio/rest/events/v1/__init__.py index d62e813d50..6b91355444 100644 --- a/twilio/rest/events/v1/__init__.py +++ b/twilio/rest/events/v1/__init__.py @@ -22,6 +22,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Events diff --git a/twilio/rest/events/v1/event_type.py b/twilio/rest/events/v1/event_type.py index beaeed332b..d00ce94b1a 100644 --- a/twilio/rest/events/v1/event_type.py +++ b/twilio/rest/events/v1/event_type.py @@ -12,10 +12,10 @@ 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 @@ -24,13 +24,14 @@ class EventTypeInstance(InstanceResource): - """ :ivar type: A string that uniquely identifies this Event Type. :ivar schema_id: A string that uniquely identifies the Schema this Event Type adheres to. :ivar date_created: The date that this Event Type was created, given in ISO 8601 format. :ivar date_updated: The date that this Event Type was updated, given in ISO 8601 format. :ivar description: A human readable description for this Event Type. + :ivar status: A string that describes how this Event Type can be used. For example: `available`, `deprecated`, `restricted`, `discontinued`. When the status is `available`, the Event Type can be used normally. + :ivar documentation_url: The URL to the documentation or to the most relevant Twilio Changelog entry of this Event Type. :ivar url: The URL of this resource. :ivar links: """ @@ -49,12 +50,15 @@ def __init__( payload.get("date_updated") ) self.description: Optional[str] = payload.get("description") + self.status: Optional[str] = payload.get("status") + self.documentation_url: Optional[str] = payload.get("documentation_url") self.url: Optional[str] = payload.get("url") self.links: Optional[Dict[str, object]] = payload.get("links") self._solution = { "type": type or self.type, } + self._context: Optional[EventTypeContext] = None @property @@ -90,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 @@ -101,6 +123,7 @@ def __repr__(self) -> str: class EventTypeContext(InstanceContext): + def __init__(self, version: Version, type: str): """ Initialize the EventTypeContext @@ -116,6 +139,22 @@ def __init__(self, version: Version, type: str): } self._uri = "/Types/{type}".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) -> EventTypeInstance: """ Fetch the EventTypeInstance @@ -123,17 +162,43 @@ def fetch(self) -> EventTypeInstance: :returns: The fetched EventTypeInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EventTypeInstance( + self._version, + payload, + type=self._solution["type"], ) - return EventTypeInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventTypeInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EventTypeInstance: """ @@ -142,17 +207,27 @@ async def fetch_async(self) -> EventTypeInstance: :returns: The fetched EventTypeInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EventTypeInstance( + self._version, + payload, + type=self._solution["type"], ) - return EventTypeInstance( + 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: """ @@ -165,12 +240,14 @@ def __repr__(self) -> str: class EventTypePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EventTypeInstance: """ Build an instance of EventTypeInstance :param payload: Payload response from the API """ + return EventTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -183,6 +260,7 @@ def __repr__(self) -> str: class EventTypeList(ListResource): + def __init__(self, version: Version): """ Initialize the EventTypeList @@ -248,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, @@ -269,6 +403,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( schema_id=schema_id, @@ -298,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( @@ -307,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, @@ -334,7 +526,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 EventTypePage(self._version, response) async def page_async( @@ -364,11 +562,91 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 5bd099d56b..5d26d6f6ab 100644 --- a/twilio/rest/events/v1/schema/__init__.py +++ b/twilio/rest/events/v1/schema/__init__.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - from datetime import datetime from typing import Any, Dict, Optional -from twilio.base import deserialize +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 @@ -25,7 +25,6 @@ class SchemaInstance(InstanceResource): - """ :ivar id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. :ivar url: The URL of this resource. @@ -42,9 +41,9 @@ def __init__( self.id: Optional[str] = payload.get("id") self.url: Optional[str] = payload.get("url") self.links: Optional[Dict[str, object]] = payload.get("links") - self.latest_version_date_created: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("latest_version_date_created")) + self.latest_version_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("latest_version_date_created")) + ) self.latest_version: Optional[int] = deserialize.integer( payload.get("latest_version") ) @@ -52,6 +51,7 @@ def __init__( self._solution = { "id": id or self.id, } + self._context: Optional[SchemaContext] = None @property @@ -87,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: """ @@ -105,6 +123,7 @@ def __repr__(self) -> str: class SchemaContext(InstanceContext): + def __init__(self, version: Version, id: str): """ Initialize the SchemaContext @@ -122,6 +141,22 @@ def __init__(self, version: Version, id: str): self._versions: Optional[SchemaVersionList] = None + 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) -> SchemaInstance: """ Fetch the SchemaInstance @@ -129,17 +164,43 @@ def fetch(self) -> SchemaInstance: :returns: The fetched SchemaInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SchemaInstance( + self._version, + payload, + id=self._solution["id"], ) - return SchemaInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SchemaInstance: """ @@ -148,17 +209,27 @@ async def fetch_async(self) -> SchemaInstance: :returns: The fetched SchemaInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SchemaInstance( + self._version, + payload, + id=self._solution["id"], ) - return SchemaInstance( + 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: @@ -183,6 +254,7 @@ def __repr__(self) -> str: class SchemaList(ListResource): + def __init__(self, version: Version): """ Initialize the SchemaList diff --git a/twilio/rest/events/v1/schema/schema_version.py b/twilio/rest/events/v1/schema/schema_version.py index 823aefbf73..d846590c83 100644 --- a/twilio/rest/events/v1/schema/schema_version.py +++ b/twilio/rest/events/v1/schema/schema_version.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class SchemaVersionInstance(InstanceResource): - """ :ivar id: The unique identifier of the schema. Each schema can have multiple versions, that share the same id. :ivar schema_version: The version of this schema. @@ -56,6 +55,7 @@ def __init__( "id": id, "schema_version": schema_version or self.schema_version, } + self._context: Optional[SchemaVersionContext] = None @property @@ -92,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 @@ -103,6 +121,7 @@ def __repr__(self) -> str: class SchemaVersionContext(InstanceContext): + def __init__(self, version: Version, id: str, schema_version: int): """ Initialize the SchemaVersionContext @@ -120,6 +139,22 @@ def __init__(self, version: Version, id: str, schema_version: int): } self._uri = "/Schemas/{id}/Versions/{schema_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) -> SchemaVersionInstance: """ Fetch the SchemaVersionInstance @@ -127,18 +162,45 @@ def fetch(self) -> SchemaVersionInstance: :returns: The fetched SchemaVersionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], ) - return SchemaVersionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SchemaVersionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SchemaVersionInstance: """ @@ -147,18 +209,29 @@ async def fetch_async(self) -> SchemaVersionInstance: :returns: The fetched SchemaVersionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SchemaVersionInstance( + self._version, + payload, + id=self._solution["id"], + schema_version=self._solution["schema_version"], ) - return SchemaVersionInstance( + 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: """ @@ -171,12 +244,14 @@ def __repr__(self) -> str: class SchemaVersionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SchemaVersionInstance: """ Build an instance of SchemaVersionInstance :param payload: Payload response from the API """ + return SchemaVersionInstance(self._version, payload, id=self._solution["id"]) def __repr__(self) -> str: @@ -189,6 +264,7 @@ def __repr__(self) -> str: class SchemaVersionList(ListResource): + def __init__(self, version: Version, id: str): """ Initialize the SchemaVersionList @@ -255,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, @@ -274,6 +400,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -300,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( @@ -308,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, @@ -332,8 +510,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SchemaVersionPage(self._version, response, self._solution) + 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 SchemaVersionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -359,10 +543,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SchemaVersionPage(self._version, response, self._solution) + 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: """ @@ -374,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: """ @@ -386,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 5a7626ad83..6bed98c16b 100644 --- a/twilio/rest/events/v1/sink/__init__.py +++ b/twilio/rest/events/v1/sink/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,10 +26,12 @@ class SinkInstance(InstanceResource): + 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: """ @@ -175,6 +238,7 @@ def __repr__(self) -> str: class SinkContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SinkContext @@ -193,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 @@ -200,9 +278,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -212,9 +312,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SinkInstance 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) -> SinkInstance: @@ -224,17 +348,43 @@ def fetch(self) -> SinkInstance: :returns: The fetched SinkInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SinkInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SinkInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SinkInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SinkInstance: """ @@ -243,62 +393,122 @@ async def fetch_async(self) -> SinkInstance: :returns: The fetched SinkInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + 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( { "Description": description, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, 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( { "Description": description, } ) + 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, + 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: """ @@ -334,12 +544,14 @@ def __repr__(self) -> str: class SinkPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SinkInstance: """ Build an instance of SinkInstance :param payload: Payload response from the API """ + return SinkInstance(self._version, payload) def __repr__(self) -> str: @@ -352,6 +564,7 @@ def __repr__(self) -> str: class SinkList(ListResource): + def __init__(self, version: Version): """ Initialize the SinkList @@ -363,6 +576,36 @@ def __init__(self, version: Version): self._uri = "/Sinks" + def _create( + self, + description: str, + sink_configuration: object, + sink_type: "SinkInstance.SinkType", + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Description": description, + "SinkConfiguration": serialize.object(sink_configuration), + "SinkType": sink_type, + } + ) + 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, description: str, @@ -378,6 +621,49 @@ def create( :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( { "Description": description, @@ -385,14 +671,15 @@ def create( "SinkType": sink_type, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SinkInstance(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, @@ -409,21 +696,35 @@ async def create_async( :returns: The created SinkInstance """ - data = values.of( - { - "Description": description, - "SinkConfiguration": serialize.object(sink_configuration), - "SinkType": sink_type, - } + payload, _, _ = await self._create_async( + description=description, + sink_configuration=sink_configuration, + sink_type=sink_type, ) + return SinkInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return SinkInstance(self._version, payload) + :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, @@ -485,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, @@ -508,6 +869,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( in_use=in_use, @@ -540,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( @@ -550,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, @@ -572,7 +997,7 @@ def page( """ data = values.of( { - "InUse": in_use, + "InUse": serialize.boolean_to_string(in_use), "Status": status, "PageToken": page_token, "Page": page_number, @@ -580,7 +1005,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SinkPage(self._version, response) async def page_async( @@ -605,7 +1036,7 @@ async def page_async( """ data = values.of( { - "InUse": in_use, + "InUse": serialize.boolean_to_string(in_use), "Status": status, "PageToken": page_token, "Page": page_number, @@ -613,11 +1044,97 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 c85c422e7b..7d253b7536 100644 --- a/twilio/rest/events/v1/sink/sink_test.py +++ b/twilio/rest/events/v1/sink/sink_test.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class SinkTestInstance(InstanceResource): - """ :ivar result: Feedback indicating whether the test event was generated. """ @@ -46,6 +46,7 @@ def __repr__(self) -> str: class SinkTestList(ListResource): + def __init__(self, version: Version, sid: str): """ Initialize the SinkTestList @@ -62,6 +63,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Sinks/{sid}/Test".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) -> SinkTestInstance: """ Create the SinkTestInstance @@ -69,13 +86,35 @@ def create(self) -> SinkTestInstance: :returns: The created SinkTestInstance """ + payload, _, _ = self._create() + return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) - payload = self._version.create( - method="POST", - uri=self._uri, - ) + def create_with_http_info(self) -> ApiResponse: + """ + Create the SinkTestInstance and return response metadata - return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + + :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) async def create_async(self) -> SinkTestInstance: """ @@ -84,13 +123,19 @@ async def create_async(self) -> SinkTestInstance: :returns: The created SinkTestInstance """ + payload, _, _ = await self._create_async() + return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - ) + async def create_with_http_info_async(self) -> ApiResponse: + """ + Asynchronously create the SinkTestInstance and return response metadata - return SinkTestInstance(self._version, payload, sid=self._solution["sid"]) + + :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: """ diff --git a/twilio/rest/events/v1/sink/sink_validate.py b/twilio/rest/events/v1/sink/sink_validate.py index 8539a1ef41..aa7a169673 100644 --- a/twilio/rest/events/v1/sink/sink_validate.py +++ b/twilio/rest/events/v1/sink/sink_validate.py @@ -12,9 +12,9 @@ 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 @@ -22,7 +22,6 @@ class SinkValidateInstance(InstanceResource): - """ :ivar result: Feedback indicating whether the given Sink was validated. """ @@ -47,6 +46,7 @@ def __repr__(self) -> str: class SinkValidateList(ListResource): + def __init__(self, version: Version, sid: str): """ Initialize the SinkValidateList @@ -63,50 +63,102 @@ 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 - - :param test_id: A 34 character string that uniquely identifies the test event for a Sink being validated. + Internal helper for create operation - :returns: The created SinkValidateInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "TestId": test_id, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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( { "TestId": test_id, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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 458177d487..f494c773c9 100644 --- a/twilio/rest/events/v1/subscription/__init__.py +++ b/twilio/rest/events/v1/subscription/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class SubscriptionInstance(InstanceResource): - """ :ivar account_sid: The unique SID identifier of the Account. :ivar sid: A 34 character string that uniquely identifies this Subscription. @@ -58,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SubscriptionContext] = None @property @@ -93,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 @@ -111,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 @@ -165,6 +221,7 @@ def __repr__(self) -> str: class SubscriptionContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SubscriptionContext @@ -182,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 @@ -189,9 +260,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -201,9 +294,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscriptionInstance 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) -> SubscriptionInstance: @@ -213,17 +330,43 @@ def fetch(self) -> SubscriptionInstance: :returns: The fetched SubscriptionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SubscriptionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscriptionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SubscriptionInstance: """ @@ -232,73 +375,135 @@ async def fetch_async(self) -> SubscriptionInstance: :returns: The fetched SubscriptionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SubscriptionInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SubscriptionInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SubscriptionInstance and return response metadata + + + :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, + } + ) + 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, - 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 """ + 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({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + 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, - 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 """ - data = values.of( - { - "Description": description, - "SinkSid": sink_sid, - } - ) + payload, _, _ = await self._update_async(description=description) + return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return SubscriptionInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -323,12 +528,14 @@ def __repr__(self) -> str: class SubscriptionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SubscriptionInstance: """ Build an instance of SubscriptionInstance :param payload: Payload response from the API """ + return SubscriptionInstance(self._version, payload) def __repr__(self) -> str: @@ -341,6 +548,7 @@ def __repr__(self) -> str: class SubscriptionList(ListResource): + def __init__(self, version: Version): """ Initialize the SubscriptionList @@ -352,6 +560,31 @@ def __init__(self, version: Version): self._uri = "/Subscriptions" + def _create(self, description: str, sink_sid: str, types: List[object]) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Description": description, + "SinkSid": sink_sid, + "Types": serialize.map(types, 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.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, description: str, sink_sid: str, types: List[object] ) -> SubscriptionInstance: @@ -364,6 +597,39 @@ def create( :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( { "Description": description, @@ -371,14 +637,15 @@ def create( "Types": serialize.map(types, lambda e: serialize.object(e)), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SubscriptionInstance(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, description: str, sink_sid: str, types: List[object] @@ -392,21 +659,28 @@ async def create_async( :returns: The created SubscriptionInstance """ - data = values.of( - { - "Description": description, - "SinkSid": sink_sid, - "Types": serialize.map(types, lambda e: serialize.object(e)), - } + payload, _, _ = await self._create_async( + description=description, sink_sid=sink_sid, types=types ) + return SubscriptionInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return SubscriptionInstance(self._version, payload) + :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, @@ -462,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, @@ -483,6 +813,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sink_sid=sink_sid, @@ -512,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( @@ -521,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, @@ -548,7 +936,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SubscriptionPage(self._version, response) async def page_async( @@ -578,11 +972,91 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 f45fe0b2e0..7ad59f767b 100644 --- a/twilio/rest/events/v1/subscription/subscribed_event.py +++ b/twilio/rest/events/v1/subscription/subscribed_event.py @@ -12,9 +12,9 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,11 +23,10 @@ class SubscribedEventInstance(InstanceResource): - """ :ivar account_sid: The unique SID identifier of the Account. :ivar type: Type of event being subscribed to. - :ivar schema_version: The schema version that the subscription should use. + :ivar schema_version: The schema version that the Subscription should use. :ivar subscription_sid: The unique SID identifier of the Subscription. :ivar url: The URL of this resource. """ @@ -53,6 +52,7 @@ def __init__( "subscription_sid": subscription_sid, "type": type or self.type, } + self._context: Optional[SubscribedEventContext] = None @property @@ -89,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 @@ -107,13 +125,31 @@ 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": """ Update the SubscribedEventInstance - :param schema_version: The schema version that the subscription should use. + :param schema_version: The schema version that the Subscription should use. :returns: The updated SubscribedEventInstance """ @@ -127,7 +163,7 @@ async def update_async( """ Asynchronous coroutine to update the SubscribedEventInstance - :param schema_version: The schema version that the subscription should use. + :param schema_version: The schema version that the Subscription should use. :returns: The updated SubscribedEventInstance """ @@ -135,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 @@ -146,6 +210,7 @@ def __repr__(self) -> str: class SubscribedEventContext(InstanceContext): + def __init__(self, version: Version, subscription_sid: str, type: str): """ Initialize the SubscribedEventContext @@ -165,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 @@ -172,9 +251,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -184,9 +285,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SubscribedEventInstance 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) -> SubscribedEventInstance: @@ -196,18 +321,45 @@ def fetch(self) -> SubscribedEventInstance: :returns: The fetched SubscribedEventInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SubscribedEventInstance( + self._version, + payload, + subscription_sid=self._solution["subscription_sid"], + type=self._solution["type"], ) - return SubscribedEventInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedEventInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SubscribedEventInstance: """ @@ -216,12 +368,7 @@ async def fetch_async(self) -> SubscribedEventInstance: :returns: The fetched SubscribedEventInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return SubscribedEventInstance( self._version, payload, @@ -229,28 +376,56 @@ 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( { "SchemaVersion": schema_version, } ) + 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, + 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, @@ -258,28 +433,61 @@ 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. + :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( { "SchemaVersion": schema_version, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -287,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 @@ -298,12 +527,14 @@ def __repr__(self) -> str: class SubscribedEventPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SubscribedEventInstance: """ Build an instance of SubscribedEventInstance :param payload: Payload response from the API """ + return SubscribedEventInstance( self._version, payload, subscription_sid=self._solution["subscription_sid"] ) @@ -318,6 +549,7 @@ def __repr__(self) -> str: class SubscribedEventList(ListResource): + def __init__(self, version: Version, subscription_sid: str): """ Initialize the SubscribedEventList @@ -336,62 +568,130 @@ 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( { "Type": type, "SchemaVersion": schema_version, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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. + :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( { "Type": type, "SchemaVersion": schema_version, } ) + 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, + 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, @@ -442,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, @@ -461,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -487,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( @@ -495,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, @@ -519,8 +921,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SubscribedEventPage(self._version, response, self._solution) + 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 SubscribedEventPage(self._version, response, solution=self._solution) async def page_async( self, @@ -546,10 +954,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SubscribedEventPage(self._version, response, self._solution) + 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: """ @@ -561,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: """ @@ -573,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/FlexApiBase.py b/twilio/rest/flex_api/FlexApiBase.py index afdad47340..3bda5b6b47 100644 --- a/twilio/rest/flex_api/FlexApiBase.py +++ b/twilio/rest/flex_api/FlexApiBase.py @@ -18,6 +18,7 @@ class FlexApiBase(Domain): + def __init__(self, twilio: Client): """ Initialize the FlexApi Domain diff --git a/twilio/rest/flex_api/v1/__init__.py b/twilio/rest/flex_api/v1/__init__.py index 64701c623f..eeb00227e9 100644 --- a/twilio/rest/flex_api/v1/__init__.py +++ b/twilio/rest/flex_api/v1/__init__.py @@ -40,10 +40,20 @@ ) from twilio.rest.flex_api.v1.insights_user_roles import InsightsUserRolesList from twilio.rest.flex_api.v1.interaction import InteractionList +from twilio.rest.flex_api.v1.plugin import PluginList +from twilio.rest.flex_api.v1.plugin_archive import PluginArchiveList +from twilio.rest.flex_api.v1.plugin_configuration import PluginConfigurationList +from twilio.rest.flex_api.v1.plugin_configuration_archive import ( + PluginConfigurationArchiveList, +) +from twilio.rest.flex_api.v1.plugin_release import PluginReleaseList +from twilio.rest.flex_api.v1.plugin_version_archive import PluginVersionArchiveList +from twilio.rest.flex_api.v1.provisioning_status import ProvisioningStatusList from twilio.rest.flex_api.v1.web_channel import WebChannelList class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of FlexApi @@ -55,9 +65,9 @@ def __init__(self, domain: Domain): self._channel: Optional[ChannelList] = None self._configuration: Optional[ConfigurationList] = None self._flex_flow: Optional[FlexFlowList] = None - self._insights_assessments_comment: Optional[ - InsightsAssessmentsCommentList - ] = None + self._insights_assessments_comment: Optional[InsightsAssessmentsCommentList] = ( + None + ) self._insights_conversations: Optional[InsightsConversationsList] = None self._insights_questionnaires: Optional[InsightsQuestionnairesList] = None self._insights_questionnaires_category: Optional[ @@ -74,6 +84,15 @@ def __init__(self, domain: Domain): self._insights_settings_comment: Optional[InsightsSettingsCommentList] = None self._insights_user_roles: Optional[InsightsUserRolesList] = None self._interaction: Optional[InteractionList] = None + self._plugins: Optional[PluginList] = None + self._plugin_archive: Optional[PluginArchiveList] = None + self._plugin_configurations: Optional[PluginConfigurationList] = None + self._plugin_configuration_archive: Optional[PluginConfigurationArchiveList] = ( + None + ) + self._plugin_releases: Optional[PluginReleaseList] = None + self._plugin_version_archive: Optional[PluginVersionArchiveList] = None + self._provisioning_status: Optional[ProvisioningStatusList] = None self._web_channel: Optional[WebChannelList] = None @property @@ -170,6 +189,48 @@ def interaction(self) -> InteractionList: self._interaction = InteractionList(self) return self._interaction + @property + def plugins(self) -> PluginList: + if self._plugins is None: + self._plugins = PluginList(self) + return self._plugins + + @property + def plugin_archive(self) -> PluginArchiveList: + if self._plugin_archive is None: + self._plugin_archive = PluginArchiveList(self) + return self._plugin_archive + + @property + def plugin_configurations(self) -> PluginConfigurationList: + if self._plugin_configurations is None: + self._plugin_configurations = PluginConfigurationList(self) + return self._plugin_configurations + + @property + def plugin_configuration_archive(self) -> PluginConfigurationArchiveList: + if self._plugin_configuration_archive is None: + self._plugin_configuration_archive = PluginConfigurationArchiveList(self) + return self._plugin_configuration_archive + + @property + def plugin_releases(self) -> PluginReleaseList: + if self._plugin_releases is None: + self._plugin_releases = PluginReleaseList(self) + return self._plugin_releases + + @property + def plugin_version_archive(self) -> PluginVersionArchiveList: + if self._plugin_version_archive is None: + self._plugin_version_archive = PluginVersionArchiveList(self) + return self._plugin_version_archive + + @property + def provisioning_status(self) -> ProvisioningStatusList: + if self._provisioning_status is None: + self._provisioning_status = ProvisioningStatusList(self) + return self._provisioning_status + @property def web_channel(self) -> WebChannelList: if self._web_channel is None: diff --git a/twilio/rest/flex_api/v1/assessments.py b/twilio/rest/flex_api/v1/assessments.py index 71f0b61383..003b309a89 100644 --- a/twilio/rest/flex_api/v1/assessments.py +++ b/twilio/rest/flex_api/v1/assessments.py @@ -12,9 +12,9 @@ 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 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 @@ -23,10 +23,9 @@ class AssessmentsInstance(InstanceResource): - """ :ivar account_sid: The unique SID identifier of the Account. - :ivar assessment_id: The unique id of the assessment + :ivar assessment_sid: The SID of the assessment :ivar offset: Offset of the conversation :ivar report: The flag indicating if this assessment is part of report :ivar weight: The weightage given to this comment @@ -45,15 +44,15 @@ def __init__( self, version: Version, payload: Dict[str, Any], - assessment_id: Optional[str] = None, + assessment_sid: Optional[str] = None, ): super().__init__(version) self.account_sid: Optional[str] = payload.get("account_sid") - self.assessment_id: Optional[str] = payload.get("assessment_id") - self.offset: Optional[float] = deserialize.decimal(payload.get("offset")) + self.assessment_sid: Optional[str] = payload.get("assessment_sid") + 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") @@ -61,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_id": assessment_id or self.assessment_id, + "assessment_sid": assessment_sid or self.assessment_sid, } + self._context: Optional[AssessmentsContext] = None @property @@ -80,7 +80,7 @@ def _proxy(self) -> "AssessmentsContext": if self._context is None: self._context = AssessmentsContext( self._version, - assessment_id=self._solution["assessment_id"], + assessment_sid=self._solution["assessment_sid"], ) return self._context @@ -89,7 +89,7 @@ def update( offset: float, answer_text: str, answer_id: str, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, ) -> "AssessmentsInstance": """ Update the AssessmentsInstance @@ -97,7 +97,7 @@ def update( :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 token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The updated AssessmentsInstance """ @@ -105,7 +105,7 @@ def update( offset=offset, answer_text=answer_text, answer_id=answer_id, - token=token, + authorization=authorization, ) async def update_async( @@ -113,7 +113,7 @@ async def update_async( offset: float, answer_text: str, answer_id: str, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, ) -> "AssessmentsInstance": """ Asynchronous coroutine to update the AssessmentsInstance @@ -121,7 +121,7 @@ async def update_async( :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 token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The updated AssessmentsInstance """ @@ -129,7 +129,55 @@ async def update_async( offset=offset, answer_text=answer_text, answer_id=answer_id, - token=token, + 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: @@ -143,27 +191,67 @@ def __repr__(self) -> str: class AssessmentsContext(InstanceContext): - def __init__(self, version: Version, assessment_id: str): + + def __init__(self, version: Version, assessment_sid: str): """ Initialize the AssessmentsContext :param version: Version that contains the resource - :param assessment_id: The id of the assessment to be modified + :param assessment_sid: The SID of the assessment to be modified """ super().__init__(version) # Path Solution self._solution = { - "assessment_id": assessment_id, + "assessment_sid": assessment_sid, } - self._uri = "/Insights/QM/Assessments/{assessment_id}".format(**self._solution) + self._uri = "/Insights/QualityManagement/Assessments/{assessment_sid}".format( + **self._solution + ) + + def _update( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Offset": offset, + "AnswerText": answer_text, + "AnswerId": answer_id, + } + ) + headers = values.of({}) + + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization + + 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, offset: float, answer_text: str, answer_id: str, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, ) -> AssessmentsInstance: """ Update the AssessmentsInstance @@ -171,10 +259,62 @@ def update( :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 token: The Token HTTP request header + :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"] + ) + + def update_with_http_info( + self, + offset: float, + answer_text: str, + answer_id: str, + authorization: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + 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 = 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( { "Offset": offset, @@ -182,18 +322,20 @@ def update( "AnswerId": answer_id, } ) - headers = values.of( - { - "Token": token, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization - return AssessmentsInstance( - self._version, payload, assessment_id=self._solution["assessment_id"] + 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( @@ -201,7 +343,7 @@ async def update_async( offset: float, answer_text: str, answer_id: str, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, ) -> AssessmentsInstance: """ Asynchronous coroutine to update the AssessmentsInstance @@ -209,30 +351,47 @@ async def update_async( :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 token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The updated AssessmentsInstance """ - data = values.of( - { - "Offset": offset, - "AnswerText": answer_text, - "AnswerId": answer_id, - } + payload, _, _ = await self._update_async( + offset=offset, + answer_text=answer_text, + answer_id=answer_id, + authorization=authorization, ) - headers = values.of( - { - "Token": token, - } + return AssessmentsInstance( + self._version, payload, assessment_sid=self._solution["assessment_sid"] ) - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return AssessmentsInstance( - self._version, payload, assessment_id=self._solution["assessment_id"] + :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: """ @@ -245,12 +404,14 @@ def __repr__(self) -> str: class AssessmentsPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AssessmentsInstance: """ Build an instance of AssessmentsInstance :param payload: Payload response from the API """ + return AssessmentsInstance(self._version, payload) def __repr__(self) -> str: @@ -263,6 +424,7 @@ def __repr__(self) -> str: class AssessmentsList(ListResource): + def __init__(self, version: Version): """ Initialize the AssessmentsList @@ -272,135 +434,297 @@ def __init__(self, version: Version): """ super().__init__(version) - self._uri = "/Insights/QM/Assessments" + self._uri = "/Insights/QualityManagement/Assessments" - def create( + def _create( self, - category_id: str, + category_sid: str, category_name: str, segment_id: str, - user_name: str, - user_email: str, agent_id: str, offset: float, metric_id: str, metric_name: str, answer_text: str, answer_id: str, - questionnaire_id: str, - token: Union[str, object] = values.unset, - ) -> AssessmentsInstance: + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, + ) -> tuple: """ - Create the AssessmentsInstance + Internal helper for create operation - :param category_id: The id of the category - :param category_name: The name of the category - :param segment_id: Segment Id of the conversation - :param user_name: Name of the user assessing conversation - :param user_email: Email of the user assessing conversation - :param agent_id: The id of the Agent - :param offset: The offset of the conversation. - :param metric_id: The question Id 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_id: Questionnaire Id of the associated question - :param token: The Token HTTP request header - - :returns: The created AssessmentsInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { - "CategoryId": category_id, + "CategorySid": category_sid, "CategoryName": category_name, "SegmentId": segment_id, - "UserName": user_name, - "UserEmail": user_email, "AgentId": agent_id, "Offset": offset, "MetricId": metric_id, "MetricName": metric_name, "AnswerText": answer_text, "AnswerId": answer_id, - "QuestionnaireId": questionnaire_id, + "QuestionnaireSid": questionnaire_sid, } ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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 ) - return AssessmentsInstance(self._version, payload) - - async def create_async( + def create( self, - category_id: str, + category_sid: str, category_name: str, segment_id: str, - user_name: str, - user_email: str, agent_id: str, offset: float, metric_id: str, metric_name: str, answer_text: str, answer_id: str, - questionnaire_id: str, - token: Union[str, object] = values.unset, + questionnaire_sid: str, + authorization: Union[str, object] = values.unset, ) -> AssessmentsInstance: """ - Asynchronously create the AssessmentsInstance + Create the AssessmentsInstance - :param category_id: The id of the category + :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 user_name: Name of the user assessing conversation - :param user_email: Email of the user assessing conversation :param agent_id: The id of the Agent :param offset: The offset of the conversation. - :param metric_id: The question Id selected for assessment + :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_id: Questionnaire Id of the associated question - :param token: The Token HTTP request header + :param questionnaire_sid: Questionnaire SID of the associated question + :param authorization: The Authorization HTTP request header :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( { - "CategoryId": category_id, + "CategorySid": category_sid, "CategoryName": category_name, "SegmentId": segment_id, - "UserName": user_name, - "UserEmail": user_email, "AgentId": agent_id, "Offset": offset, "MetricId": metric_id, "MetricName": metric_name, "AnswerText": answer_text, "AnswerId": answer_id, - "QuestionnaireId": questionnaire_id, + "QuestionnaireSid": questionnaire_sid, } ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -411,7 +735,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -424,14 +748,16 @@ def stream( """ limits = self._version.read_limits(limit, page_size) page = self.page( - token=token, segment_id=segment_id, page_size=limits["page_size"] + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], ) return self._version.stream(page, limits["limit"]) async def stream_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -442,7 +768,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -455,14 +781,80 @@ async def stream_async( """ limits = self._version.read_limits(limit, page_size) page = await self.page_async( - token=token, segment_id=segment_id, page_size=limits["page_size"] + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], ) 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -472,7 +864,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -483,9 +875,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( - token=token, + authorization=authorization, segment_id=segment_id, limit=limit, page_size=page_size, @@ -494,7 +887,7 @@ def list( async def list_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -504,7 +897,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -515,19 +908,82 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( - token=token, + authorization=authorization, segment_id=segment_id, limit=limit, page_size=page_size, ) ] + 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, - token: Union[str, object] = values.unset, + 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, @@ -537,7 +993,7 @@ def page( Retrieve a single page of AssessmentsInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -547,7 +1003,7 @@ def page( """ data = values.of( { - "Token": token, + "Authorization": authorization, "SegmentId": segment_id, "PageToken": page_token, "Page": page_number, @@ -555,12 +1011,23 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + headers = values.of( + { + "Authorization": authorization, + "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 AssessmentsPage(self._version, response) async def page_async( self, - token: Union[str, object] = values.unset, + 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, @@ -570,7 +1037,7 @@ async def page_async( Asynchronously retrieve a single page of AssessmentsInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -580,7 +1047,7 @@ async def page_async( """ data = values.of( { - "Token": token, + "Authorization": authorization, "SegmentId": segment_id, "PageToken": page_token, "Page": page_number, @@ -588,11 +1055,112 @@ async def page_async( } ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + response = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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. @@ -617,21 +1185,21 @@ async def get_page_async(self, target_url: str) -> AssessmentsPage: response = await self._version.domain.twilio.request_async("GET", target_url) return AssessmentsPage(self._version, response) - def get(self, assessment_id: str) -> AssessmentsContext: + def get(self, assessment_sid: str) -> AssessmentsContext: """ Constructs a AssessmentsContext - :param assessment_id: The id of the assessment to be modified + :param assessment_sid: The SID of the assessment to be modified """ - return AssessmentsContext(self._version, assessment_id=assessment_id) + return AssessmentsContext(self._version, assessment_sid=assessment_sid) - def __call__(self, assessment_id: str) -> AssessmentsContext: + def __call__(self, assessment_sid: str) -> AssessmentsContext: """ Constructs a AssessmentsContext - :param assessment_id: The id of the assessment to be modified + :param assessment_sid: The SID of the assessment to be modified """ - return AssessmentsContext(self._version, assessment_id=assessment_id) + return AssessmentsContext(self._version, assessment_sid=assessment_sid) def __repr__(self) -> str: """ diff --git a/twilio/rest/flex_api/v1/channel.py b/twilio/rest/flex_api/v1/channel.py index cf2d765879..0f223bc426 100644 --- a/twilio/rest/flex_api/v1/channel.py +++ b/twilio/rest/flex_api/v1/channel.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class ChannelInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Channel resource and owns this Workflow. :ivar flex_flow_sid: The SID of the Flex Flow. @@ -57,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ChannelContext] = None @property @@ -92,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 @@ -110,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 @@ -121,6 +157,7 @@ def __repr__(self) -> str: class ChannelContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ChannelContext @@ -136,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 @@ -143,9 +194,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -155,9 +228,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance 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) -> ChannelInstance: @@ -167,17 +264,43 @@ def fetch(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ChannelInstance: """ @@ -186,17 +309,27 @@ async def fetch_async(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ChannelInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ChannelInstance( + 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: """ @@ -209,12 +342,14 @@ def __repr__(self) -> str: class ChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ Build an instance of ChannelInstance :param payload: Payload response from the API """ + return ChannelInstance(self._version, payload) def __repr__(self) -> str: @@ -227,6 +362,7 @@ def __repr__(self) -> str: class ChannelList(ListResource): + def __init__(self, version: Version): """ Initialize the ChannelList @@ -238,6 +374,50 @@ def __init__(self, version: Version): self._uri = "/Channels" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "ChatUserFriendlyName": chat_user_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "Target": target, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + "TaskSid": task_sid, + "TaskAttributes": task_attributes, + "LongLived": serialize.boolean_to_string(long_lived), + } + ) + 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, flex_flow_sid: str, @@ -267,6 +447,84 @@ def create( :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( { "FlexFlowSid": flex_flow_sid, @@ -278,17 +536,18 @@ def create( "PreEngagementData": pre_engagement_data, "TaskSid": task_sid, "TaskAttributes": task_attributes, - "LongLived": long_lived, + "LongLived": serialize.boolean_to_string(long_lived), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ChannelInstance(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, @@ -319,28 +578,63 @@ async def create_async( :returns: The created ChannelInstance """ - data = values.of( - { - "FlexFlowSid": flex_flow_sid, - "Identity": identity, - "ChatUserFriendlyName": chat_user_friendly_name, - "ChatFriendlyName": chat_friendly_name, - "Target": target, - "ChatUniqueName": chat_unique_name, - "PreEngagementData": pre_engagement_data, - "TaskSid": task_sid, - "TaskAttributes": task_attributes, - "LongLived": long_lived, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return ChannelInstance(self._version, payload) + :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, @@ -392,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, @@ -411,6 +755,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -437,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( @@ -445,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, @@ -469,7 +865,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 ChannelPage(self._version, response) async def page_async( @@ -496,11 +898,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 741a4c40f8..6e8f586a01 100644 --- a/twilio/rest/flex_api/v1/configuration.py +++ b/twilio/rest/flex_api/v1/configuration.py @@ -12,10 +12,10 @@ 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 @@ -23,6 +23,7 @@ class ConfigurationInstance(InstanceResource): + class Status(object): OK = "ok" INPROGRESS = "inprogress" @@ -46,6 +47,7 @@ class Status(object): :ivar messaging_service_instance_sid: The SID of the Messaging service instance. :ivar chat_service_instance_sid: The SID of the chat service this user belongs to. :ivar flex_service_instance_sid: The SID of the Flex service instance. + :ivar flex_instance_sid: The SID of the Flex instance. :ivar ui_language: The primary language of the Flex UI. :ivar ui_attributes: The object that describes Flex UI characteristics and settings. :ivar ui_dependencies: The object that defines the NPM packages and versions to be used in Hosted Flex. @@ -74,6 +76,9 @@ class Status(object): :ivar channel_configs: Settings for different limits for Flex Conversations channels attachments. :ivar debugger_integration: Configurable parameters for Debugger Integration. :ivar flex_ui_status_report: Configurable parameters for Flex UI Status report. + :ivar agent_conv_end_methods: Agent conversation end methods. + :ivar citrix_voice_vdi: Citrix voice vdi configuration and settings. + :ivar offline_config: Presence and presence ttl configuration """ def __init__(self, version: Version, payload: Dict[str, Any]): @@ -97,10 +102,10 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.taskrouter_target_taskqueue_sid: Optional[str] = payload.get( "taskrouter_target_taskqueue_sid" ) - self.taskrouter_taskqueues: Optional[List[object]] = payload.get( + self.taskrouter_taskqueues: Optional[List[Dict[str, object]]] = payload.get( "taskrouter_taskqueues" ) - self.taskrouter_skills: Optional[List[object]] = payload.get( + self.taskrouter_skills: Optional[List[Dict[str, object]]] = payload.get( "taskrouter_skills" ) self.taskrouter_worker_channels: Optional[Dict[str, object]] = payload.get( @@ -122,6 +127,7 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.flex_service_instance_sid: Optional[str] = payload.get( "flex_service_instance_sid" ) + self.flex_instance_sid: Optional[str] = payload.get("flex_instance_sid") self.ui_language: Optional[str] = payload.get("ui_language") self.ui_attributes: Optional[Dict[str, object]] = payload.get("ui_attributes") self.ui_dependencies: Optional[Dict[str, object]] = payload.get( @@ -149,7 +155,9 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.plugin_service_attributes: Optional[Dict[str, object]] = payload.get( "plugin_service_attributes" ) - self.integrations: Optional[List[object]] = payload.get("integrations") + self.integrations: Optional[List[Dict[str, object]]] = payload.get( + "integrations" + ) self.outbound_call_flows: Optional[Dict[str, object]] = payload.get( "outbound_call_flows" ) @@ -169,13 +177,22 @@ def __init__(self, version: Version, payload: Dict[str, Any]): "flex_insights_drilldown" ) self.flex_url: Optional[str] = payload.get("flex_url") - self.channel_configs: Optional[List[object]] = payload.get("channel_configs") + self.channel_configs: Optional[List[Dict[str, object]]] = payload.get( + "channel_configs" + ) self.debugger_integration: Optional[Dict[str, object]] = payload.get( "debugger_integration" ) self.flex_ui_status_report: Optional[Dict[str, object]] = payload.get( "flex_ui_status_report" ) + self.agent_conv_end_methods: Optional[Dict[str, object]] = payload.get( + "agent_conv_end_methods" + ) + self.citrix_voice_vdi: Optional[Dict[str, object]] = payload.get( + "citrix_voice_vdi" + ) + self.offline_config: Optional[Dict[str, object]] = payload.get("offline_config") self._context: Optional[ConfigurationContext] = None @@ -221,6 +238,90 @@ 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": + """ + Update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + return self._proxy.update( + body=body, + ) + + async def update_async( + self, body: Union[object, object] = values.unset + ) -> "ConfigurationInstance": + """ + Asynchronous coroutine to update the ConfigurationInstance + + :param body: + + :returns: The updated ConfigurationInstance + """ + return await self._proxy.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 @@ -232,6 +333,7 @@ def __repr__(self) -> str: class ConfigurationContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the ConfigurationContext @@ -242,6 +344,28 @@ def __init__(self, version: Version): self._uri = "/Configuration" + def _fetch(self, ui_version: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "UiVersion": ui_version, + } + ) + + 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, ui_version: Union[str, object] = values.unset ) -> ConfigurationInstance: @@ -252,18 +376,51 @@ def fetch( :returns: The fetched ConfigurationInstance """ + payload, _, _ = self._fetch(ui_version=ui_version) + return ConfigurationInstance( + self._version, + payload, + ) + + def fetch_with_http_info( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfigurationInstance and return response metadata - data = values.of( + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :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 + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "UiVersion": ui_version, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + headers = values.of({}) - return ConfigurationInstance( - self._version, - payload, + 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( @@ -276,21 +433,120 @@ async def fetch_async( :returns: The fetched ConfigurationInstance """ - - data = values.of( - { - "UiVersion": ui_version, - } + payload, _, _ = await self._fetch_async(ui_version=ui_version) + return ConfigurationInstance( + self._version, + payload, ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + async def fetch_with_http_info_async( + self, ui_version: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConfigurationInstance and return response metadata - return ConfigurationInstance( + :param ui_version: The Pinned UI version of the Configuration resource to fetch. + + :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() + + 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 + ) -> 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({}) + + 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 + ) -> 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: """ @@ -303,6 +559,7 @@ def __repr__(self) -> str: class ConfigurationList(ListResource): + def __init__(self, version: Version): """ Initialize the ConfigurationList diff --git a/twilio/rest/flex_api/v1/flex_flow.py b/twilio/rest/flex_api/v1/flex_flow.py index 45402a43b6..35f61b0683 100644 --- a/twilio/rest/flex_api/v1/flex_flow.py +++ b/twilio/rest/flex_api/v1/flex_flow.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class FlexFlowInstance(InstanceResource): + class ChannelType(object): WEB = "web" SMS = "sms" @@ -74,9 +75,9 @@ def __init__( ) self.contact_identity: Optional[str] = payload.get("contact_identity") self.enabled: Optional[bool] = payload.get("enabled") - self.integration_type: Optional[ - "FlexFlowInstance.IntegrationType" - ] = payload.get("integration_type") + self.integration_type: Optional["FlexFlowInstance.IntegrationType"] = ( + payload.get("integration_type") + ) self.integration: Optional[Dict[str, object]] = payload.get("integration") self.long_lived: Optional[bool] = payload.get("long_lived") self.janitor_enabled: Optional[bool] = payload.get("janitor_enabled") @@ -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 @@ -279,6 +447,7 @@ def __repr__(self) -> str: class FlexFlowContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the FlexFlowContext @@ -294,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 @@ -301,9 +484,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -313,9 +518,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlexFlowInstance 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) -> FlexFlowInstance: @@ -325,17 +554,43 @@ def fetch(self) -> FlexFlowInstance: :returns: The fetched FlexFlowInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FlexFlowInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlexFlowInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FlexFlowInstance: """ @@ -344,19 +599,29 @@ async def fetch_async(self) -> FlexFlowInstance: :returns: The fetched FlexFlowInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return FlexFlowInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FlexFlowInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, chat_service_sid: Union[str, object] = values.unset, @@ -377,37 +642,21 @@ 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( { "FriendlyName": friendly_name, "ChatServiceSid": chat_service_sid, "ChannelType": channel_type, "ContactIdentity": contact_identity, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "IntegrationType": integration_type, "Integration.FlowSid": integration_flow_sid, "Integration.Url": integration_url, @@ -416,22 +665,25 @@ def update( "Integration.Channel": integration_channel, "Integration.Timeout": integration_timeout, "Integration.Priority": integration_priority, - "Integration.CreationOnMessage": integration_creation_on_message, - "LongLived": long_lived, - "JanitorEnabled": janitor_enabled, + "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({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - async def update_async( + 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, chat_service_sid: Union[str, object] = values.unset, @@ -454,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. @@ -476,36 +728,289 @@ async def update_async( :returns: The updated FlexFlowInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "ChatServiceSid": chat_service_sid, - "ChannelType": channel_type, - "ContactIdentity": contact_identity, - "Enabled": 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": integration_creation_on_message, - "LongLived": long_lived, - "JanitorEnabled": janitor_enabled, - "Integration.RetryCount": integration_retry_count, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FlexFlowInstance(self._version, payload, sid=self._solution["sid"]) - + 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"]) + + 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), + "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({}) + + 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, + 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 @@ -517,36 +1022,296 @@ def __repr__(self) -> str: class FlexFlowPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> FlexFlowInstance: """ Build an instance of FlexFlowInstance :param payload: Payload response from the API """ + return FlexFlowInstance(self._version, payload) def __repr__(self) -> str: """ - Provide a friendly representation + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class FlexFlowList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlexFlowList + + :param version: Version that contains the resource + + """ + 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: Machine friendly representation + Returns: + tuple: (payload, status_code, headers) """ - return "" + 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"}) -class FlexFlowList(ListResource): - def __init__(self, version: Version): - """ - Initialize the FlexFlowList - - :param version: Version that contains the resource + headers["Content-Type"] = "application/x-www-form-urlencoded" - """ - super().__init__(version) + 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, @@ -569,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. @@ -591,37 +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": 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": integration_creation_on_message, - "LongLived": long_lived, - "JanitorEnabled": janitor_enabled, - "Integration.RetryCount": integration_retry_count, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, @@ -642,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. @@ -664,37 +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": 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": integration_creation_on_message, - "LongLived": long_lived, - "JanitorEnabled": janitor_enabled, - "Integration.RetryCount": integration_retry_count, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, @@ -752,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, @@ -773,6 +1577,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -802,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( @@ -811,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, @@ -838,7 +1700,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 FlexFlowPage(self._version, response) async def page_async( @@ -868,11 +1736,91 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 d8f339910c..0f48ce1cc5 100644 --- a/twilio/rest/flex_api/v1/insights_assessments_comment.py +++ b/twilio/rest/flex_api/v1/insights_assessments_comment.py @@ -12,9 +12,9 @@ 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 import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,10 +23,9 @@ class InsightsAssessmentsCommentInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. - :ivar assessment_id: The unique ID of the assessment. + :ivar assessment_sid: The SID of the assessment. :ivar comment: The comment added for assessment. :ivar offset: The offset :ivar report: The flag indicating if this assessment is part of report @@ -43,16 +42,16 @@ def __init__(self, version: Version, payload: Dict[str, Any]): super().__init__(version) self.account_sid: Optional[str] = payload.get("account_sid") - self.assessment_id: Optional[str] = payload.get("assessment_id") + 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: @@ -66,6 +65,7 @@ def __repr__(self) -> str: class InsightsAssessmentsCommentPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> InsightsAssessmentsCommentInstance: @@ -74,6 +74,7 @@ def get_instance( :param payload: Payload response from the API """ + return InsightsAssessmentsCommentInstance(self._version, payload) def __repr__(self) -> str: @@ -86,6 +87,7 @@ def __repr__(self) -> str: class InsightsAssessmentsCommentList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsAssessmentsCommentList @@ -95,111 +97,233 @@ def __init__(self, version: Version): """ super().__init__(version) - self._uri = "/Insights/QM/Assessments/Comments" + self._uri = "/Insights/QualityManagement/Assessments/Comments" - def create( + def _create( self, category_id: str, category_name: str, comment: str, segment_id: str, - user_name: str, - user_email: str, agent_id: str, offset: float, - token: Union[str, object] = values.unset, - ) -> InsightsAssessmentsCommentInstance: + authorization: Union[str, object] = values.unset, + ) -> 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 user_name: The name of the user. - :param user_email: The email id of the user. - :param agent_id: The id of the agent. - :param offset: The offset - :param token: The Token HTTP request header - - :returns: The created InsightsAssessmentsCommentInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "CategoryId": category_id, "CategoryName": category_name, "Comment": comment, "SegmentId": segment_id, - "UserName": user_name, - "UserEmail": user_email, "AgentId": agent_id, "Offset": offset, } ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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 ) - return InsightsAssessmentsCommentInstance(self._version, payload) - - async def create_async( + def create( self, category_id: str, category_name: str, comment: str, segment_id: str, - user_name: str, - user_email: str, agent_id: str, offset: float, - token: Union[str, object] = values.unset, + 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 :param comment: The Assessment comment. :param segment_id: The id of the segment. - :param user_name: The name of the user. - :param user_email: The email id of the user. :param agent_id: The id of the agent. :param offset: The offset - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :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( { "CategoryId": category_id, "CategoryName": category_name, "Comment": comment, "SegmentId": segment_id, - "UserName": user_name, - "UserEmail": user_email, "AgentId": agent_id, "Offset": offset, } ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, agent_id: Union[str, object] = values.unset, limit: Optional[int] = None, @@ -211,7 +335,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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() @@ -225,7 +349,7 @@ def stream( """ limits = self._version.read_limits(limit, page_size) page = self.page( - token=token, + authorization=authorization, segment_id=segment_id, agent_id=agent_id, page_size=limits["page_size"], @@ -235,7 +359,7 @@ def stream( async def stream_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, agent_id: Union[str, object] = values.unset, limit: Optional[int] = None, @@ -247,7 +371,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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() @@ -261,7 +385,7 @@ async def stream_async( """ limits = self._version.read_limits(limit, page_size) page = await self.page_async( - token=token, + authorization=authorization, segment_id=segment_id, agent_id=agent_id, page_size=limits["page_size"], @@ -269,9 +393,79 @@ 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, agent_id: Union[str, object] = values.unset, limit: Optional[int] = None, @@ -282,7 +476,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -294,9 +488,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( - token=token, + authorization=authorization, segment_id=segment_id, agent_id=agent_id, limit=limit, @@ -306,7 +501,7 @@ def list( async def list_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, agent_id: Union[str, object] = values.unset, limit: Optional[int] = None, @@ -317,7 +512,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -329,10 +524,11 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( - token=token, + authorization=authorization, segment_id=segment_id, agent_id=agent_id, limit=limit, @@ -340,9 +536,77 @@ 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, - token: Union[str, object] = values.unset, + 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, @@ -353,7 +617,7 @@ def page( Retrieve a single page of InsightsAssessmentsCommentInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -364,7 +628,7 @@ def page( """ data = values.of( { - "Token": token, + "Authorization": authorization, "SegmentId": segment_id, "AgentId": agent_id, "PageToken": page_token, @@ -373,12 +637,23 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + headers = values.of( + { + "Authorization": authorization, + "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 InsightsAssessmentsCommentPage(self._version, response) async def page_async( self, - token: Union[str, object] = values.unset, + 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, @@ -389,7 +664,7 @@ async def page_async( Asynchronously retrieve a single page of InsightsAssessmentsCommentInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -400,7 +675,7 @@ async def page_async( """ data = values.of( { - "Token": token, + "Authorization": authorization, "SegmentId": segment_id, "AgentId": agent_id, "PageToken": page_token, @@ -409,11 +684,118 @@ async def page_async( } ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + response = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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 aa1d806948..c407089755 100644 --- a/twilio/rest/flex_api/v1/insights_conversations.py +++ b/twilio/rest/flex_api/v1/insights_conversations.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class InsightsConversationsInstance(InstanceResource): - """ :ivar account_id: The id of the account. :ivar conversation_id: The unique id of the conversation @@ -39,7 +38,7 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.segment_count: Optional[int] = deserialize.integer( payload.get("segment_count") ) - self.segments: Optional[List[object]] = payload.get("segments") + self.segments: Optional[List[Dict[str, object]]] = payload.get("segments") def __repr__(self) -> str: """ @@ -52,12 +51,14 @@ def __repr__(self) -> str: class InsightsConversationsPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InsightsConversationsInstance: """ Build an instance of InsightsConversationsInstance :param payload: Payload response from the API """ + return InsightsConversationsInstance(self._version, payload) def __repr__(self) -> str: @@ -70,6 +71,7 @@ def __repr__(self) -> str: class InsightsConversationsList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsConversationsList @@ -83,7 +85,7 @@ def __init__(self, version: Version): def stream( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -94,7 +96,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -107,14 +109,16 @@ def stream( """ limits = self._version.read_limits(limit, page_size) page = self.page( - token=token, segment_id=segment_id, page_size=limits["page_size"] + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], ) return self._version.stream(page, limits["limit"]) async def stream_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -125,7 +129,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -138,14 +142,80 @@ async def stream_async( """ limits = self._version.read_limits(limit, page_size) page = await self.page_async( - token=token, segment_id=segment_id, page_size=limits["page_size"] + authorization=authorization, + segment_id=segment_id, + page_size=limits["page_size"], ) 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -155,7 +225,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -166,9 +236,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( - token=token, + authorization=authorization, segment_id=segment_id, limit=limit, page_size=page_size, @@ -177,7 +248,7 @@ def list( async def list_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, segment_id: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -187,7 +258,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -198,19 +269,82 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( - token=token, + authorization=authorization, segment_id=segment_id, limit=limit, page_size=page_size, ) ] + 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, - token: Union[str, object] = values.unset, + 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, @@ -220,7 +354,7 @@ def page( Retrieve a single page of InsightsConversationsInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -230,7 +364,7 @@ def page( """ data = values.of( { - "Token": token, + "Authorization": authorization, "SegmentId": segment_id, "PageToken": page_token, "Page": page_number, @@ -238,12 +372,23 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + headers = values.of( + { + "Authorization": authorization, + "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 InsightsConversationsPage(self._version, response) async def page_async( self, - token: Union[str, object] = values.unset, + 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, @@ -253,7 +398,7 @@ async def page_async( Asynchronously retrieve a single page of InsightsConversationsInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -263,7 +408,7 @@ async def page_async( """ data = values.of( { - "Token": token, + "Authorization": authorization, "SegmentId": segment_id, "PageToken": page_token, "Page": page_number, @@ -271,11 +416,112 @@ async def page_async( } ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + response = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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 b86378b2d1..3ecf2f8156 100644 --- a/twilio/rest/flex_api/v1/insights_questionnaires.py +++ b/twilio/rest/flex_api/v1/insights_questionnaires.py @@ -12,9 +12,9 @@ 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.api_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,10 +23,9 @@ class InsightsQuestionnairesInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. - :ivar id: The unique id of this questionnaire + :ivar questionnaire_sid: The sid of this questionnaire :ivar name: The name of this category. :ivar description: The description of this questionnaire :ivar active: The flag to enable or disable questionnaire @@ -35,21 +34,25 @@ class InsightsQuestionnairesInstance(InstanceResource): """ def __init__( - self, version: Version, payload: Dict[str, Any], id: Optional[str] = None + self, + version: Version, + payload: Dict[str, Any], + questionnaire_sid: Optional[str] = None, ): super().__init__(version) self.account_sid: Optional[str] = payload.get("account_sid") - self.id: Optional[str] = payload.get("id") + self.questionnaire_sid: Optional[str] = payload.get("questionnaire_sid") self.name: Optional[str] = payload.get("name") self.description: Optional[str] = payload.get("description") self.active: Optional[bool] = payload.get("active") - self.questions: Optional[List[object]] = payload.get("questions") + self.questions: Optional[List[Dict[str, object]]] = payload.get("questions") self.url: Optional[str] = payload.get("url") self._solution = { - "id": id or self.id, + "questionnaire_sid": questionnaire_sid or self.questionnaire_sid, } + self._context: Optional[InsightsQuestionnairesContext] = None @property @@ -63,114 +66,226 @@ def _proxy(self) -> "InsightsQuestionnairesContext": if self._context is None: self._context = InsightsQuestionnairesContext( self._version, - id=self._solution["id"], + questionnaire_sid=self._solution["questionnaire_sid"], ) return self._context - def delete(self, token: Union[str, object] = values.unset) -> bool: + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: True if delete succeeds, False otherwise """ return self._proxy.delete( - token=token, + authorization=authorization, ) - async def delete_async(self, token: Union[str, object] = values.unset) -> bool: + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: """ Asynchronous coroutine that deletes the InsightsQuestionnairesInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: True if delete succeeds, False otherwise """ return await self._proxy.delete_async( - token=token, + 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, token: Union[str, object] = values.unset + self, authorization: Union[str, object] = values.unset ) -> "InsightsQuestionnairesInstance": """ Fetch the InsightsQuestionnairesInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The fetched InsightsQuestionnairesInstance """ return self._proxy.fetch( - token=token, + authorization=authorization, ) async def fetch_async( - self, token: Union[str, object] = values.unset + self, authorization: Union[str, object] = values.unset ) -> "InsightsQuestionnairesInstance": """ Asynchronous coroutine to fetch the InsightsQuestionnairesInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The fetched InsightsQuestionnairesInstance """ return await self._proxy.fetch_async( - token=token, + 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - question_ids: Union[List[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 token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :param name: The name of this questionnaire :param description: The description of this questionnaire - :param question_ids: The list of questions ids under a questionnaire + :param question_sids: The list of questions sids under a questionnaire :returns: The updated InsightsQuestionnairesInstance """ return self._proxy.update( active=active, - token=token, + authorization=authorization, name=name, description=description, - question_ids=question_ids, + question_sids=question_sids, ) async def update_async( self, active: bool, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - question_ids: Union[List[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 token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :param name: The name of this questionnaire :param description: The description of this questionnaire - :param question_ids: The list of questions ids under a questionnaire + :param question_sids: The list of questions sids under a questionnaire :returns: The updated InsightsQuestionnairesInstance """ return await self._proxy.update_async( active=active, - token=token, + authorization=authorization, name=name, description=description, - question_ids=question_ids, + 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: @@ -184,188 +299,443 @@ def __repr__(self) -> str: class InsightsQuestionnairesContext(InstanceContext): - def __init__(self, version: Version, id: str): + + def __init__(self, version: Version, questionnaire_sid: str): """ Initialize the InsightsQuestionnairesContext :param version: Version that contains the resource - :param id: The unique ID of the questionnaire + :param questionnaire_sid: The SID of the questionnaire """ super().__init__(version) # Path Solution self._solution = { - "id": id, + "questionnaire_sid": questionnaire_sid, } - self._uri = "/Insights/QM/Questionnaires/{id}".format(**self._solution) + self._uri = ( + "/Insights/QualityManagement/Questionnaires/{questionnaire_sid}".format( + **self._solution + ) + ) - def delete(self, token: Union[str, object] = values.unset) -> bool: + def _delete(self, authorization: Union[str, object] = values.unset) -> tuple: """ - Deletes the InsightsQuestionnairesInstance - - :param token: The Token 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( { - "Token": token, + "Authorization": authorization, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) - async def delete_async(self, token: Union[str, object] = values.unset) -> bool: + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ - Asynchronous coroutine that deletes the InsightsQuestionnairesInstance + Deletes the InsightsQuestionnairesInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :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( { - "Token": token, + "Authorization": authorization, } ) - return await self._version.delete_async( + headers = values.of({}) + + 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 + ) -> bool: + """ + Asynchronous coroutine that deletes the InsightsQuestionnairesInstance + + :param authorization: The Authorization HTTP request header + + :returns: True if delete succeeds, False otherwise + """ + 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({}) + + 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, token: Union[str, object] = values.unset + self, authorization: Union[str, object] = values.unset ) -> InsightsQuestionnairesInstance: """ Fetch the InsightsQuestionnairesInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The fetched InsightsQuestionnairesInstance """ - - data = values.of( - { - "Token": token, - } + payload, _, _ = self._fetch(authorization=authorization) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsQuestionnairesInstance and return response metadata - return InsightsQuestionnairesInstance( + :param authorization: The Authorization HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._fetch(authorization=authorization) + instance = InsightsQuestionnairesInstance( self._version, payload, - id=self._solution["id"], + 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, token: Union[str, object] = values.unset + self, authorization: Union[str, object] = values.unset ) -> InsightsQuestionnairesInstance: """ Asynchronous coroutine to fetch the InsightsQuestionnairesInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The fetched InsightsQuestionnairesInstance """ + payload, _, _ = await self._fetch_async(authorization=authorization) + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + + 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 + + :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 = InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], + ) + return ApiResponse(data=instance, status_code=status_code, 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { - "Token": token, + "Active": serialize.boolean_to_string(active), + "Name": name, + "Description": description, + "QuestionSids": serialize.map(question_sids, lambda e: e), } ) + headers = values.of({}) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization - return InsightsQuestionnairesInstance( - self._version, - payload, - id=self._solution["id"], + 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, active: bool, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - question_ids: Union[List[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 token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :param name: The name of this questionnaire :param description: The description of this questionnaire - :param question_ids: The list of questions ids under a 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"], + ) + + 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 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 = 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( { - "Active": active, + "Active": serialize.boolean_to_string(active), "Name": name, "Description": description, - "QuestionIds": serialize.map(question_ids, lambda e: e), - } - ) - headers = values.of( - { - "Token": token, + "QuestionSids": serialize.map(question_sids, lambda e: e), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization - return InsightsQuestionnairesInstance( - self._version, payload, id=self._solution["id"] + 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, active: bool, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, name: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - question_ids: Union[List[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 token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :param name: The name of this questionnaire :param description: The description of this questionnaire - :param question_ids: The list of questions ids under a questionnaire + :param question_sids: The list of questions sids under a questionnaire :returns: The updated InsightsQuestionnairesInstance """ - data = values.of( - { - "Active": active, - "Name": name, - "Description": description, - "QuestionIds": serialize.map(question_ids, lambda e: e), - } + payload, _, _ = await self._update_async( + active=active, + authorization=authorization, + name=name, + description=description, + question_sids=question_sids, ) - headers = values.of( - { - "Token": token, - } + return InsightsQuestionnairesInstance( + self._version, + payload, + questionnaire_sid=self._solution["questionnaire_sid"], ) - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return InsightsQuestionnairesInstance( - self._version, payload, id=self._solution["id"] + :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: """ @@ -378,12 +748,14 @@ def __repr__(self) -> str: class InsightsQuestionnairesPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InsightsQuestionnairesInstance: """ Build an instance of InsightsQuestionnairesInstance :param payload: Payload response from the API """ + return InsightsQuestionnairesInstance(self._version, payload) def __repr__(self) -> str: @@ -396,6 +768,7 @@ def __repr__(self) -> str: class InsightsQuestionnairesList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsQuestionnairesList @@ -405,87 +778,201 @@ def __init__(self, version: Version): """ super().__init__(version) - self._uri = "/Insights/QM/Questionnaires" + self._uri = "/Insights/QualityManagement/Questionnaires" - def create( + def _create( self, name: str, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, description: Union[str, object] = values.unset, active: Union[bool, object] = values.unset, - question_ids: Union[List[str], object] = values.unset, - ) -> InsightsQuestionnairesInstance: + question_sids: Union[List[str], object] = values.unset, + ) -> tuple: """ - Create the InsightsQuestionnairesInstance + Internal helper for create operation - :param name: The name of this questionnaire - :param token: The Token HTTP request header - :param description: The description of this questionnaire - :param active: The flag to enable or disable questionnaire - :param question_ids: The list of questions ids under a questionnaire - - :returns: The created InsightsQuestionnairesInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Name": name, "Description": description, - "Active": active, - "QuestionIds": serialize.map(question_ids, lambda e: e), + "Active": serialize.boolean_to_string(active), + "QuestionSids": serialize.map(question_sids, lambda e: e), } ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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 ) - return InsightsQuestionnairesInstance(self._version, payload) - - async def create_async( + def create( self, name: str, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, description: Union[str, object] = values.unset, active: Union[bool, object] = values.unset, - question_ids: Union[List[str], object] = values.unset, + question_sids: Union[List[str], object] = values.unset, ) -> InsightsQuestionnairesInstance: """ - Asynchronously create the InsightsQuestionnairesInstance + Create the InsightsQuestionnairesInstance :param name: The name of this questionnaire - :param token: The Token HTTP request header + :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_ids: The list of questions ids under a questionnaire + :param question_sids: The list of questions sids under a questionnaire :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( { "Name": name, "Description": description, - "Active": active, - "QuestionIds": serialize.map(question_ids, lambda e: e), + "Active": serialize.boolean_to_string(active), + "QuestionSids": serialize.map(question_sids, lambda e: e), } ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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: 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, include_inactive: Union[bool, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -496,7 +983,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -509,7 +996,7 @@ def stream( """ limits = self._version.read_limits(limit, page_size) page = self.page( - token=token, + authorization=authorization, include_inactive=include_inactive, page_size=limits["page_size"], ) @@ -518,7 +1005,7 @@ def stream( async def stream_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, include_inactive: Union[bool, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -529,7 +1016,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -542,16 +1029,80 @@ async def stream_async( """ limits = self._version.read_limits(limit, page_size) page = await self.page_async( - token=token, + authorization=authorization, include_inactive=include_inactive, page_size=limits["page_size"], ) 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, include_inactive: Union[bool, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -561,7 +1112,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -572,9 +1123,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( - token=token, + authorization=authorization, include_inactive=include_inactive, limit=limit, page_size=page_size, @@ -583,7 +1135,7 @@ def list( async def list_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, include_inactive: Union[bool, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, @@ -593,7 +1145,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -604,19 +1156,82 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( - token=token, + authorization=authorization, include_inactive=include_inactive, limit=limit, page_size=page_size, ) ] + 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, - token: Union[str, object] = values.unset, + 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, @@ -626,7 +1241,7 @@ def page( Retrieve a single page of InsightsQuestionnairesInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -636,20 +1251,31 @@ def page( """ data = values.of( { - "Token": token, - "IncludeInactive": include_inactive, + "Authorization": authorization, + "IncludeInactive": serialize.boolean_to_string(include_inactive), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + headers = values.of( + { + "Authorization": authorization, + "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 InsightsQuestionnairesPage(self._version, response) async def page_async( self, - token: Union[str, object] = values.unset, + 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, @@ -659,7 +1285,7 @@ async def page_async( Asynchronously retrieve a single page of InsightsQuestionnairesInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -669,19 +1295,120 @@ async def page_async( """ data = values.of( { - "Token": token, - "IncludeInactive": include_inactive, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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. @@ -706,21 +1433,25 @@ async def get_page_async(self, target_url: str) -> InsightsQuestionnairesPage: response = await self._version.domain.twilio.request_async("GET", target_url) return InsightsQuestionnairesPage(self._version, response) - def get(self, id: str) -> InsightsQuestionnairesContext: + def get(self, questionnaire_sid: str) -> InsightsQuestionnairesContext: """ Constructs a InsightsQuestionnairesContext - :param id: The unique ID of the questionnaire + :param questionnaire_sid: The SID of the questionnaire """ - return InsightsQuestionnairesContext(self._version, id=id) + return InsightsQuestionnairesContext( + self._version, questionnaire_sid=questionnaire_sid + ) - def __call__(self, id: str) -> InsightsQuestionnairesContext: + def __call__(self, questionnaire_sid: str) -> InsightsQuestionnairesContext: """ Constructs a InsightsQuestionnairesContext - :param id: The unique ID of the questionnaire + :param questionnaire_sid: The SID of the questionnaire """ - return InsightsQuestionnairesContext(self._version, id=id) + return InsightsQuestionnairesContext( + self._version, questionnaire_sid=questionnaire_sid + ) def __repr__(self) -> str: """ diff --git a/twilio/rest/flex_api/v1/insights_questionnaires_category.py b/twilio/rest/flex_api/v1/insights_questionnaires_category.py index 35dc3da2df..9cc42e866a 100644 --- a/twilio/rest/flex_api/v1/insights_questionnaires_category.py +++ b/twilio/rest/flex_api/v1/insights_questionnaires_category.py @@ -12,9 +12,9 @@ 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 @@ -23,10 +23,9 @@ class InsightsQuestionnairesCategoryInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. - :ivar category_id: The unique ID for the category + :ivar category_sid: The SID of the category :ivar name: The name of this category. :ivar url: """ @@ -35,18 +34,19 @@ def __init__( self, version: Version, payload: Dict[str, Any], - category_id: Optional[str] = None, + category_sid: Optional[str] = None, ): super().__init__(version) self.account_sid: Optional[str] = payload.get("account_sid") - self.category_id: Optional[str] = payload.get("category_id") + self.category_sid: Optional[str] = payload.get("category_sid") self.name: Optional[str] = payload.get("name") self.url: Optional[str] = payload.get("url") self._solution = { - "category_id": category_id or self.category_id, + "category_sid": category_sid or self.category_sid, } + self._context: Optional[InsightsQuestionnairesCategoryContext] = None @property @@ -60,64 +60,126 @@ def _proxy(self) -> "InsightsQuestionnairesCategoryContext": if self._context is None: self._context = InsightsQuestionnairesCategoryContext( self._version, - category_id=self._solution["category_id"], + category_sid=self._solution["category_sid"], ) return self._context - def delete(self, token: Union[str, object] = values.unset) -> bool: + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesCategoryInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: True if delete succeeds, False otherwise """ return self._proxy.delete( - token=token, + authorization=authorization, ) - async def delete_async(self, token: Union[str, object] = values.unset) -> bool: + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: """ Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: True if delete succeeds, False otherwise """ return await self._proxy.delete_async( - token=token, + 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, token: Union[str, object] = values.unset + self, name: str, authorization: Union[str, object] = values.unset ) -> "InsightsQuestionnairesCategoryInstance": """ Update the InsightsQuestionnairesCategoryInstance :param name: The name of this category. - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The updated InsightsQuestionnairesCategoryInstance """ return self._proxy.update( name=name, - token=token, + authorization=authorization, ) async def update_async( - self, name: str, token: Union[str, object] = values.unset + self, name: str, authorization: Union[str, object] = values.unset ) -> "InsightsQuestionnairesCategoryInstance": """ Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance :param name: The name of this category. - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The updated InsightsQuestionnairesCategoryInstance """ return await self._proxy.update_async( name=name, - token=token, + 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: @@ -133,114 +195,247 @@ def __repr__(self) -> str: class InsightsQuestionnairesCategoryContext(InstanceContext): - def __init__(self, version: Version, category_id: str): + + def __init__(self, version: Version, category_sid: str): """ Initialize the InsightsQuestionnairesCategoryContext :param version: Version that contains the resource - :param category_id: The ID of the category to be update + :param category_sid: The SID of the category to be updated """ super().__init__(version) # Path Solution self._solution = { - "category_id": category_id, + "category_sid": category_sid, } - self._uri = "/Insights/QM/Categories/{category_id}".format(**self._solution) + self._uri = "/Insights/QualityManagement/Categories/{category_sid}".format( + **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, token: Union[str, object] = values.unset) -> bool: + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesCategoryInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :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( { - "Token": token, + "Authorization": authorization, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=headers) + headers = values.of({}) - async def delete_async(self, token: Union[str, object] = values.unset) -> bool: + 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 + ) -> bool: """ Asynchronous coroutine that deletes the InsightsQuestionnairesCategoryInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: True if delete succeeds, False otherwise """ - headers = values.of( + 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 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 = await self._delete_async( + authorization=authorization + ) + return ApiResponse(data=success, status_code=status_code, headers=headers) + + def _update( + self, name: str, authorization: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( { - "Token": token, + "Name": name, } ) + 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["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, name: str, token: Union[str, object] = values.unset + self, name: str, authorization: Union[str, object] = values.unset ) -> InsightsQuestionnairesCategoryInstance: """ Update the InsightsQuestionnairesCategoryInstance :param name: The name of this category. - :param token: The Token HTTP request header + :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"] + ) + + def update_with_http_info( + self, name: str, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "Name": name, } ) - headers = values.of( - { - "Token": token, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization - return InsightsQuestionnairesCategoryInstance( - self._version, payload, category_id=self._solution["category_id"] + 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, name: str, token: Union[str, object] = values.unset + self, name: str, authorization: Union[str, object] = values.unset ) -> InsightsQuestionnairesCategoryInstance: """ Asynchronous coroutine to update the InsightsQuestionnairesCategoryInstance :param name: The name of this category. - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: The updated InsightsQuestionnairesCategoryInstance """ - data = values.of( - { - "Name": name, - } - ) - headers = values.of( - { - "Token": token, - } + payload, _, _ = await self._update_async(name=name, authorization=authorization) + return InsightsQuestionnairesCategoryInstance( + self._version, payload, category_sid=self._solution["category_sid"] ) - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return InsightsQuestionnairesCategoryInstance( - self._version, payload, category_id=self._solution["category_id"] + :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: """ @@ -255,6 +450,7 @@ def __repr__(self) -> str: class InsightsQuestionnairesCategoryPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> InsightsQuestionnairesCategoryInstance: @@ -263,6 +459,7 @@ def get_instance( :param payload: Payload response from the API """ + return InsightsQuestionnairesCategoryInstance(self._version, payload) def __repr__(self) -> str: @@ -275,6 +472,7 @@ def __repr__(self) -> str: class InsightsQuestionnairesCategoryList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsQuestionnairesCategoryList @@ -284,19 +482,18 @@ def __init__(self, version: Version): """ super().__init__(version) - self._uri = "/Insights/QM/Categories" + self._uri = "/Insights/QualityManagement/Categories" - def create( - self, name: str, token: Union[str, object] = values.unset - ) -> InsightsQuestionnairesCategoryInstance: + def _create( + self, name: str, authorization: Union[str, object] = values.unset + ) -> tuple: """ - Create the InsightsQuestionnairesCategoryInstance + Internal helper for create operation - :param name: The name of this category. - :param token: The Token HTTP request header - - :returns: The created InsightsQuestionnairesCategoryInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Name": name, @@ -304,26 +501,60 @@ def create( ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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 ) - return InsightsQuestionnairesCategoryInstance(self._version, payload) - - async def create_async( - self, name: str, token: Union[str, object] = values.unset + 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 token: The Token HTTP request header + :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( { "Name": name, @@ -331,18 +562,53 @@ async def create_async( ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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: 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[InsightsQuestionnairesCategoryInstance]: @@ -352,7 +618,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -363,13 +629,13 @@ def stream( :returns: Generator that will yield up to limit results """ limits = self._version.read_limits(limit, page_size) - page = self.page(token=token, page_size=limits["page_size"]) + page = self.page(authorization=authorization, page_size=limits["page_size"]) return self._version.stream(page, limits["limit"]) async def stream_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[InsightsQuestionnairesCategoryInstance]: @@ -379,7 +645,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -390,13 +656,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(token=token, page_size=limits["page_size"]) + page = await self.page_async( + authorization=authorization, page_size=limits["page_size"] + ) 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, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[InsightsQuestionnairesCategoryInstance]: @@ -405,7 +729,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -415,9 +739,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( - token=token, + authorization=authorization, limit=limit, page_size=page_size, ) @@ -425,7 +750,7 @@ def list( async def list_async( self, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[InsightsQuestionnairesCategoryInstance]: @@ -434,7 +759,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -444,18 +769,75 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( - token=token, + authorization=authorization, limit=limit, page_size=page_size, ) ] + 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, - token: Union[str, object] = values.unset, + 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, @@ -464,7 +846,7 @@ def page( Retrieve a single page of InsightsQuestionnairesCategoryInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -473,19 +855,30 @@ def page( """ data = values.of( { - "Token": token, + "Authorization": authorization, "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + headers = values.of( + { + "Authorization": authorization, + "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 InsightsQuestionnairesCategoryPage(self._version, response) async def page_async( self, - token: Union[str, object] = values.unset, + 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, @@ -494,7 +887,7 @@ async def page_async( Asynchronously retrieve a single page of InsightsQuestionnairesCategoryInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -503,18 +896,113 @@ async def page_async( """ data = values.of( { - "Token": token, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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. @@ -541,24 +1029,24 @@ async def get_page_async( response = await self._version.domain.twilio.request_async("GET", target_url) return InsightsQuestionnairesCategoryPage(self._version, response) - def get(self, category_id: str) -> InsightsQuestionnairesCategoryContext: + def get(self, category_sid: str) -> InsightsQuestionnairesCategoryContext: """ Constructs a InsightsQuestionnairesCategoryContext - :param category_id: The ID of the category to be update + :param category_sid: The SID of the category to be updated """ return InsightsQuestionnairesCategoryContext( - self._version, category_id=category_id + self._version, category_sid=category_sid ) - def __call__(self, category_id: str) -> InsightsQuestionnairesCategoryContext: + def __call__(self, category_sid: str) -> InsightsQuestionnairesCategoryContext: """ Constructs a InsightsQuestionnairesCategoryContext - :param category_id: The ID of the category to be update + :param category_sid: The SID of the category to be updated """ return InsightsQuestionnairesCategoryContext( - self._version, category_id=category_id + self._version, category_sid=category_sid ) def __repr__(self) -> str: diff --git a/twilio/rest/flex_api/v1/insights_questionnaires_question.py b/twilio/rest/flex_api/v1/insights_questionnaires_question.py index a0cfe55262..e8a88190b6 100644 --- a/twilio/rest/flex_api/v1/insights_questionnaires_question.py +++ b/twilio/rest/flex_api/v1/insights_questionnaires_question.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - 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,10 +23,9 @@ class InsightsQuestionnairesQuestionInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. - :ivar question_id: The unique ID of the question + :ivar question_sid: The SID of the question :ivar question: The question. :ivar description: The description for the question. :ivar category: The Category for the question. @@ -41,12 +40,12 @@ def __init__( self, version: Version, payload: Dict[str, Any], - question_id: Optional[str] = None, + question_sid: Optional[str] = None, ): super().__init__(version) self.account_sid: Optional[str] = payload.get("account_sid") - self.question_id: Optional[str] = payload.get("question_id") + self.question_sid: Optional[str] = payload.get("question_sid") self.question: Optional[str] = payload.get("question") self.description: Optional[str] = payload.get("description") self.category: Optional[Dict[str, object]] = payload.get("category") @@ -57,8 +56,9 @@ def __init__( self.url: Optional[str] = payload.get("url") self._solution = { - "question_id": question_id or self.question_id, + "question_sid": question_sid or self.question_sid, } + self._context: Optional[InsightsQuestionnairesQuestionContext] = None @property @@ -72,39 +72,69 @@ def _proxy(self) -> "InsightsQuestionnairesQuestionContext": if self._context is None: self._context = InsightsQuestionnairesQuestionContext( self._version, - question_id=self._solution["question_id"], + question_sid=self._solution["question_sid"], ) return self._context - def delete(self, token: Union[str, object] = values.unset) -> bool: + def delete(self, authorization: Union[str, object] = values.unset) -> bool: """ Deletes the InsightsQuestionnairesQuestionInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: True if delete succeeds, False otherwise """ return self._proxy.delete( - token=token, + authorization=authorization, ) - async def delete_async(self, token: Union[str, object] = values.unset) -> bool: + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: """ Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: True if delete succeeds, False otherwise """ return await self._proxy.delete_async( - token=token, + 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, - token: Union[str, object] = values.unset, - category_id: Union[str, object] = values.unset, + 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, @@ -113,8 +143,8 @@ def update( Update the InsightsQuestionnairesQuestionInstance :param allow_na: The flag to enable for disable NA for answer. - :param token: The Token HTTP request header - :param category_id: The ID of the category + :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. @@ -123,8 +153,8 @@ def update( """ return self._proxy.update( allow_na=allow_na, - token=token, - category_id=category_id, + authorization=authorization, + category_sid=category_sid, question=question, description=description, answer_set_id=answer_set_id, @@ -133,8 +163,8 @@ def update( async def update_async( self, allow_na: bool, - token: Union[str, object] = values.unset, - category_id: Union[str, object] = values.unset, + 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, @@ -143,8 +173,8 @@ async def update_async( Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance :param allow_na: The flag to enable for disable NA for answer. - :param token: The Token HTTP request header - :param category_id: The ID of the category + :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. @@ -153,8 +183,68 @@ async def update_async( """ return await self._proxy.update_async( allow_na=allow_na, - token=token, - category_id=category_id, + authorization=authorization, + category_sid=category_sid, + question=question, + description=description, + 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, @@ -173,60 +263,162 @@ def __repr__(self) -> str: class InsightsQuestionnairesQuestionContext(InstanceContext): - def __init__(self, version: Version, question_id: str): + + def __init__(self, version: Version, question_sid: str): """ Initialize the InsightsQuestionnairesQuestionContext :param version: Version that contains the resource - :param question_id: The unique ID of the question + :param question_sid: The SID of the question """ super().__init__(version) # Path Solution self._solution = { - "question_id": question_id, + "question_sid": question_sid, } - self._uri = "/Insights/QM/Questions/{question_id}".format(**self._solution) + self._uri = "/Insights/QualityManagement/Questions/{question_sid}".format( + **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, + } + ) - def delete(self, token: Union[str, object] = values.unset) -> bool: + 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 - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :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( { - "Token": token, + "Authorization": authorization, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, token: Union[str, object] = values.unset) -> bool: + async def delete_async( + self, authorization: Union[str, object] = values.unset + ) -> bool: """ Asynchronous coroutine that deletes the InsightsQuestionnairesQuestionInstance - :param token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :returns: True if delete succeeds, False otherwise """ - headers = values.of( + 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 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 = await self._delete_async( + authorization=authorization + ) + return ApiResponse(data=success, status_code=status_code, 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( { - "Token": token, + "AllowNa": serialize.boolean_to_string(allow_na), + "CategorySid": category_sid, + "Question": question, + "Description": description, + "AnswerSetId": answer_set_id, } ) + 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["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, allow_na: bool, - token: Union[str, object] = values.unset, - category_id: Union[str, object] = values.unset, + 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, @@ -235,42 +427,106 @@ def update( Update the InsightsQuestionnairesQuestionInstance :param allow_na: The flag to enable for disable NA for answer. - :param token: The Token HTTP request header - :param category_id: The ID of the category + :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"] + ) + + 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 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 = 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( { - "AllowNa": allow_na, - "CategoryId": category_id, + "AllowNa": serialize.boolean_to_string(allow_na), + "CategorySid": category_sid, "Question": question, "Description": description, "AnswerSetId": answer_set_id, } ) - headers = values.of( - { - "Token": token, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + if not ( + authorization is values.unset + or (isinstance(authorization, str) and not authorization) + ): + headers["Authorization"] = authorization - return InsightsQuestionnairesQuestionInstance( - self._version, payload, question_id=self._solution["question_id"] + 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, allow_na: bool, - token: Union[str, object] = values.unset, - category_id: Union[str, object] = values.unset, + 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, @@ -279,36 +535,59 @@ async def update_async( Asynchronous coroutine to update the InsightsQuestionnairesQuestionInstance :param allow_na: The flag to enable for disable NA for answer. - :param token: The Token HTTP request header - :param category_id: The ID of the category + :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 """ - data = values.of( - { - "AllowNa": allow_na, - "CategoryId": category_id, - "Question": question, - "Description": description, - "AnswerSetId": answer_set_id, - } + 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, ) - headers = values.of( - { - "Token": token, - } + return InsightsQuestionnairesQuestionInstance( + self._version, payload, question_sid=self._solution["question_sid"] ) - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return InsightsQuestionnairesQuestionInstance( - self._version, payload, question_id=self._solution["question_id"] + :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: """ @@ -323,6 +602,7 @@ def __repr__(self) -> str: class InsightsQuestionnairesQuestionPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> InsightsQuestionnairesQuestionInstance: @@ -331,6 +611,7 @@ def get_instance( :param payload: Payload response from the API """ + return InsightsQuestionnairesQuestionInstance(self._version, payload) def __repr__(self) -> str: @@ -343,6 +624,7 @@ def __repr__(self) -> str: class InsightsQuestionnairesQuestionList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsQuestionnairesQuestionList @@ -352,94 +634,218 @@ def __init__(self, version: Version): """ super().__init__(version) - self._uri = "/Insights/QM/Questions" + self._uri = "/Insights/QualityManagement/Questions" - def create( + def _create( self, - category_id: str, + category_sid: str, question: str, answer_set_id: str, allow_na: bool, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, description: Union[str, object] = values.unset, - ) -> InsightsQuestionnairesQuestionInstance: + ) -> tuple: """ - Create the InsightsQuestionnairesQuestionInstance + Internal helper for create operation - :param category_id: The ID 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 token: The Token HTTP request header - :param description: The description for the question. - - :returns: The created InsightsQuestionnairesQuestionInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { - "CategoryId": category_id, + "CategorySid": category_sid, "Question": question, "AnswerSetId": answer_set_id, - "AllowNa": allow_na, + "AllowNa": serialize.boolean_to_string(allow_na), "Description": description, } ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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 ) - return InsightsQuestionnairesQuestionInstance(self._version, payload) - - async def create_async( + def create( self, - category_id: str, + category_sid: str, question: str, answer_set_id: str, allow_na: bool, - token: Union[str, object] = values.unset, + authorization: Union[str, object] = values.unset, description: Union[str, object] = values.unset, ) -> InsightsQuestionnairesQuestionInstance: """ - Asynchronously create the InsightsQuestionnairesQuestionInstance + Create the InsightsQuestionnairesQuestionInstance - :param category_id: The ID of the category + :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 token: The Token HTTP request header + :param authorization: The Authorization HTTP request header :param description: The description for the question. :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) + + 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( { - "CategoryId": category_id, + "CategorySid": category_sid, "Question": question, "AnswerSetId": answer_set_id, - "AllowNa": allow_na, + "AllowNa": serialize.boolean_to_string(allow_na), "Description": description, } ) headers = values.of( { - "Token": token, + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, - token: Union[str, object] = values.unset, - category_id: Union[List[str], object] = values.unset, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[InsightsQuestionnairesQuestionInstance]: @@ -449,8 +855,8 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header - :param List[str] category_id: The list of category IDs + :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 @@ -462,15 +868,17 @@ def stream( """ limits = self._version.read_limits(limit, page_size) page = self.page( - token=token, category_id=category_id, page_size=limits["page_size"] + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], ) return self._version.stream(page, limits["limit"]) async def stream_async( self, - token: Union[str, object] = values.unset, - category_id: Union[List[str], object] = values.unset, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[InsightsQuestionnairesQuestionInstance]: @@ -480,8 +888,8 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header - :param List[str] category_id: The list of category IDs + :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 @@ -493,15 +901,81 @@ async def stream_async( """ limits = self._version.read_limits(limit, page_size) page = await self.page_async( - token=token, category_id=category_id, page_size=limits["page_size"] + authorization=authorization, + category_sid=category_sid, + page_size=limits["page_size"], ) 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, - token: Union[str, object] = values.unset, - category_id: Union[List[str], object] = values.unset, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[InsightsQuestionnairesQuestionInstance]: @@ -510,8 +984,8 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header - :param List[str] category_id: The list of category IDs + :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 @@ -521,10 +995,11 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( - token=token, - category_id=category_id, + authorization=authorization, + category_sid=category_sid, limit=limit, page_size=page_size, ) @@ -532,8 +1007,8 @@ def list( async def list_async( self, - token: Union[str, object] = values.unset, - category_id: Union[List[str], object] = values.unset, + authorization: Union[str, object] = values.unset, + category_sid: Union[List[str], object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[InsightsQuestionnairesQuestionInstance]: @@ -542,8 +1017,8 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header - :param List[str] category_id: The list of category IDs + :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 @@ -553,20 +1028,83 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( - token=token, - category_id=category_id, + authorization=authorization, + category_sid=category_sid, limit=limit, page_size=page_size, ) ] + 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, - token: Union[str, object] = values.unset, - category_id: Union[List[str], object] = values.unset, + 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, @@ -575,8 +1113,8 @@ def page( Retrieve a single page of InsightsQuestionnairesQuestionInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header - :param category_id: The list of category IDs + :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 @@ -585,21 +1123,32 @@ def page( """ data = values.of( { - "Token": token, - "CategoryId": serialize.map(category_id, lambda e: e), + "Authorization": authorization, + "CategorySid": serialize.map(category_sid, lambda e: e), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + headers = values.of( + { + "Authorization": authorization, + "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 InsightsQuestionnairesQuestionPage(self._version, response) async def page_async( self, - token: Union[str, object] = values.unset, - category_id: Union[List[str], object] = values.unset, + 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, @@ -608,8 +1157,8 @@ async def page_async( Asynchronously retrieve a single page of InsightsQuestionnairesQuestionInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header - :param category_id: The list of category IDs + :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 @@ -618,19 +1167,120 @@ async def page_async( """ data = values.of( { - "Token": token, - "CategoryId": serialize.map(category_id, lambda e: e), + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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. @@ -657,24 +1307,24 @@ async def get_page_async( response = await self._version.domain.twilio.request_async("GET", target_url) return InsightsQuestionnairesQuestionPage(self._version, response) - def get(self, question_id: str) -> InsightsQuestionnairesQuestionContext: + def get(self, question_sid: str) -> InsightsQuestionnairesQuestionContext: """ Constructs a InsightsQuestionnairesQuestionContext - :param question_id: The unique ID of the question + :param question_sid: The SID of the question """ return InsightsQuestionnairesQuestionContext( - self._version, question_id=question_id + self._version, question_sid=question_sid ) - def __call__(self, question_id: str) -> InsightsQuestionnairesQuestionContext: + def __call__(self, question_sid: str) -> InsightsQuestionnairesQuestionContext: """ Constructs a InsightsQuestionnairesQuestionContext - :param question_id: The unique ID of the question + :param question_sid: The SID of the question """ return InsightsQuestionnairesQuestionContext( - self._version, question_id=question_id + self._version, question_sid=question_sid ) def __repr__(self) -> str: diff --git a/twilio/rest/flex_api/v1/insights_segments.py b/twilio/rest/flex_api/v1/insights_segments.py index 68eb689200..e5232a323a 100644 --- a/twilio/rest/flex_api/v1/insights_segments.py +++ b/twilio/rest/flex_api/v1/insights_segments.py @@ -12,10 +12,10 @@ 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.api_response import ApiResponse + from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource from twilio.base.version import Version @@ -23,7 +23,6 @@ class InsightsSegmentsInstance(InstanceResource): - """ :ivar segment_id: To unique id of the segment :ivar external_id: The unique id for the conversation. @@ -49,12 +48,7 @@ class InsightsSegmentsInstance(InstanceResource): :ivar url: """ - def __init__( - self, - version: Version, - payload: Dict[str, Any], - segment_id: Optional[str] = None, - ): + def __init__(self, version: Version, payload: Dict[str, Any]): super().__init__(version) self.segment_id: Optional[str] = payload.get("segment_id") @@ -90,149 +84,25 @@ def __init__( ) self.url: Optional[str] = payload.get("url") - self._solution = { - "segment_id": segment_id or self.segment_id, - } - self._context: Optional[InsightsSegmentsContext] = None - - @property - def _proxy(self) -> "InsightsSegmentsContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: InsightsSegmentsContext for this InsightsSegmentsInstance - """ - if self._context is None: - self._context = InsightsSegmentsContext( - self._version, - segment_id=self._solution["segment_id"], - ) - return self._context - - def fetch( - self, token: Union[str, object] = values.unset - ) -> "InsightsSegmentsInstance": - """ - Fetch the InsightsSegmentsInstance - - :param token: The Token HTTP request header - - :returns: The fetched InsightsSegmentsInstance - """ - return self._proxy.fetch( - token=token, - ) - - async def fetch_async( - self, token: Union[str, object] = values.unset - ) -> "InsightsSegmentsInstance": - """ - Asynchronous coroutine to fetch the InsightsSegmentsInstance - - :param token: The Token HTTP request header - - :returns: The fetched InsightsSegmentsInstance - """ - return await self._proxy.fetch_async( - token=token, - ) - 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 InsightsSegmentsContext(InstanceContext): - def __init__(self, version: Version, segment_id: str): - """ - Initialize the InsightsSegmentsContext - - :param version: Version that contains the resource - :param segment_id: To unique id of the segment - """ - super().__init__(version) - - # Path Solution - self._solution = { - "segment_id": segment_id, - } - self._uri = "/Insights/Segments/{segment_id}".format(**self._solution) - - def fetch( - self, token: Union[str, object] = values.unset - ) -> InsightsSegmentsInstance: - """ - Fetch the InsightsSegmentsInstance - - :param token: The Token HTTP request header - - :returns: The fetched InsightsSegmentsInstance - """ - - data = values.of( - { - "Token": token, - } - ) - - payload = self._version.fetch(method="GET", uri=self._uri, params=data) - - return InsightsSegmentsInstance( - self._version, - payload, - segment_id=self._solution["segment_id"], - ) - - async def fetch_async( - self, token: Union[str, object] = values.unset - ) -> InsightsSegmentsInstance: - """ - Asynchronous coroutine to fetch the InsightsSegmentsInstance - - :param token: The Token HTTP request header - - :returns: The fetched InsightsSegmentsInstance - """ - - data = values.of( - { - "Token": token, - } - ) - - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) - - return InsightsSegmentsInstance( - self._version, - payload, - segment_id=self._solution["segment_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) + return "" class InsightsSegmentsPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InsightsSegmentsInstance: """ Build an instance of InsightsSegmentsInstance :param payload: Payload response from the API """ + return InsightsSegmentsInstance(self._version, payload) def __repr__(self) -> str: @@ -245,6 +115,7 @@ def __repr__(self) -> str: class InsightsSegmentsList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsSegmentsList @@ -258,7 +129,8 @@ def __init__(self, version: Version): def stream( self, - token: Union[str, object] = values.unset, + 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, @@ -269,7 +141,8 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -282,14 +155,18 @@ def stream( """ limits = self._version.read_limits(limit, page_size) page = self.page( - token=token, reservation_id=reservation_id, page_size=limits["page_size"] + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], ) return self._version.stream(page, limits["limit"]) async def stream_async( self, - token: Union[str, object] = values.unset, + 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, @@ -300,7 +177,8 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str token: The Token HTTP request header + :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 @@ -313,14 +191,88 @@ async def stream_async( """ limits = self._version.read_limits(limit, page_size) page = await self.page_async( - token=token, reservation_id=reservation_id, page_size=limits["page_size"] + authorization=authorization, + segment_id=segment_id, + reservation_id=reservation_id, + page_size=limits["page_size"], ) 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, - token: Union[str, object] = values.unset, + 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, @@ -330,7 +282,8 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -341,9 +294,11 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( - token=token, + authorization=authorization, + segment_id=segment_id, reservation_id=reservation_id, limit=limit, page_size=page_size, @@ -352,7 +307,8 @@ def list( async def list_async( self, - token: Union[str, object] = values.unset, + 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, @@ -362,7 +318,8 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str token: The Token HTTP request header + :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 @@ -373,19 +330,90 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( - token=token, + authorization=authorization, + segment_id=segment_id, reservation_id=reservation_id, limit=limit, page_size=page_size, ) ] + 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, - token: Union[str, object] = values.unset, + 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, @@ -395,7 +423,8 @@ def page( Retrieve a single page of InsightsSegmentsInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -405,7 +434,8 @@ def page( """ data = values.of( { - "Token": token, + "Authorization": authorization, + "SegmentId": segment_id, "ReservationId": serialize.map(reservation_id, lambda e: e), "PageToken": page_token, "Page": page_number, @@ -413,12 +443,24 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + headers = values.of( + { + "Authorization": authorization, + "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 InsightsSegmentsPage(self._version, response) async def page_async( self, - token: Union[str, object] = values.unset, + 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, @@ -428,7 +470,8 @@ async def page_async( Asynchronously retrieve a single page of InsightsSegmentsInstance records from the API. Request is executed immediately - :param token: The Token HTTP request header + :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 @@ -438,7 +481,8 @@ async def page_async( """ data = values.of( { - "Token": token, + "Authorization": authorization, + "SegmentId": segment_id, "ReservationId": serialize.map(reservation_id, lambda e: e), "PageToken": page_token, "Page": page_number, @@ -446,11 +490,118 @@ async def page_async( } ) + headers = values.of( + { + "Authorization": authorization, + "Content-Type": "application/x-www-form-urlencoded", + } + ) + + headers["Accept"] = "application/json" + response = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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. @@ -475,22 +626,6 @@ async def get_page_async(self, target_url: str) -> InsightsSegmentsPage: response = await self._version.domain.twilio.request_async("GET", target_url) return InsightsSegmentsPage(self._version, response) - def get(self, segment_id: str) -> InsightsSegmentsContext: - """ - Constructs a InsightsSegmentsContext - - :param segment_id: To unique id of the segment - """ - return InsightsSegmentsContext(self._version, segment_id=segment_id) - - def __call__(self, segment_id: str) -> InsightsSegmentsContext: - """ - Constructs a InsightsSegmentsContext - - :param segment_id: To unique id of the segment - """ - return InsightsSegmentsContext(self._version, segment_id=segment_id) - def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/flex_api/v1/insights_session.py b/twilio/rest/flex_api/v1/insights_session.py index d0b889822e..d633933625 100644 --- a/twilio/rest/flex_api/v1/insights_session.py +++ b/twilio/rest/flex_api/v1/insights_session.py @@ -12,9 +12,9 @@ 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 @@ -22,7 +22,6 @@ class InsightsSessionInstance(InstanceResource): - """ :ivar workspace_id: Unique ID to identify the user's workspace :ivar session_expiry: The session expiry date and time, given in ISO 8601 format. @@ -84,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 @@ -95,6 +122,7 @@ def __repr__(self) -> str: class InsightsSessionContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the InsightsSessionContext @@ -105,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: @@ -115,15 +166,47 @@ def create( :returns: The created InsightsSessionInstance """ - data = values.of( - { - "Authorization": authorization, - } - ) + payload, _, _ = self._create(authorization=authorization) + return InsightsSessionInstance(self._version, payload) + + def create_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Create the InsightsSessionInstance and return response metadata - payload = self._version.create(method="POST", uri=self._uri, data=data) + :param authorization: The Authorization HTTP request header - return InsightsSessionInstance(self._version, payload) + :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 @@ -135,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: """ @@ -158,6 +248,7 @@ def __repr__(self) -> str: class InsightsSessionList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsSessionList 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 f93fc0db62..8f6938ded8 100644 --- a/twilio/rest/flex_api/v1/insights_settings_answer_sets.py +++ b/twilio/rest/flex_api/v1/insights_settings_answer_sets.py @@ -12,8 +12,9 @@ Do not edit the class manually. """ - -from typing import Any, Dict, Optional +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 @@ -21,7 +22,6 @@ class InsightsSettingsAnswerSetsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. :ivar answer_sets: The lis of answer sets @@ -52,6 +52,7 @@ def __repr__(self) -> str: class InsightsSettingsAnswerSetsList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsSettingsAnswerSetsList @@ -61,28 +62,102 @@ def __init__(self, version: Version): """ super().__init__(version) - self._uri = "/Insights/QM/Settings/AnswerSets" + self._uri = "/Insights/QualityManagement/Settings/AnswerSets" - def fetch(self) -> InsightsSettingsAnswerSetsInstance: + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: """ - Asynchronously fetch the InsightsSettingsAnswerSetsInstance + Internal helper for fetch operation - :returns: The fetched InsightsSettingsAnswerSetsInstance + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of( + { + "Authorization": authorization, + "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, authorization: Union[str, object] = values.unset + ) -> InsightsSettingsAnswerSetsInstance: """ - payload = self._version.fetch(method="GET", uri=self._uri) + Fetch the InsightsSettingsAnswerSetsInstance + :param authorization: The Authorization HTTP request header + :returns: The fetched InsightsSettingsAnswerSetsInstance + """ + payload, _, _ = self._fetch(authorization=authorization) return InsightsSettingsAnswerSetsInstance(self._version, payload) - async def fetch_async(self) -> InsightsSettingsAnswerSetsInstance: + 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, + "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, 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._version.fetch_async(method="GET", uri=self._uri) - + 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 4d848ce980..44ca4f4d36 100644 --- a/twilio/rest/flex_api/v1/insights_settings_comment.py +++ b/twilio/rest/flex_api/v1/insights_settings_comment.py @@ -12,8 +12,9 @@ Do not edit the class manually. """ - -from typing import Any, Dict, Optional +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 @@ -21,7 +22,6 @@ class InsightsSettingsCommentInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Insights resource and owns this resource. :ivar comments: @@ -46,6 +46,7 @@ def __repr__(self) -> str: class InsightsSettingsCommentList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsSettingsCommentList @@ -55,28 +56,102 @@ def __init__(self, version: Version): """ super().__init__(version) - self._uri = "/Insights/QM/Settings/CommentTags" + self._uri = "/Insights/QualityManagement/Settings/CommentTags" - def fetch(self) -> InsightsSettingsCommentInstance: + def _fetch(self, authorization: Union[str, object] = values.unset) -> tuple: """ - Asynchronously fetch the InsightsSettingsCommentInstance + Internal helper for fetch operation - :returns: The fetched InsightsSettingsCommentInstance + Returns: + tuple: (payload, status_code, headers) """ - payload = self._version.fetch(method="GET", uri=self._uri) + headers = values.of( + { + "Authorization": authorization, + "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, authorization: Union[str, object] = values.unset + ) -> 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) - async def fetch_async(self) -> InsightsSettingsCommentInstance: + 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, + "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, 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._version.fetch_async(method="GET", uri=self._uri) - + 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 25d406bcb2..33ef7c663a 100644 --- a/twilio/rest/flex_api/v1/insights_user_roles.py +++ b/twilio/rest/flex_api/v1/insights_user_roles.py @@ -12,9 +12,9 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,7 +22,6 @@ class InsightsUserRolesInstance(InstanceResource): - """ :ivar roles: Flex Insights roles for the user :ivar url: @@ -78,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 @@ -89,6 +116,7 @@ def __repr__(self) -> str: class InsightsUserRolesContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the InsightsUserRolesContext @@ -99,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: @@ -109,19 +159,52 @@ def fetch( :returns: The fetched InsightsUserRolesInstance """ - - data = values.of( - { - "Authorization": authorization, - } + payload, _, _ = self._fetch(authorization=authorization) + return InsightsUserRolesInstance( + self._version, + payload, ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + def fetch_with_http_info( + self, authorization: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the InsightsUserRolesInstance and return response metadata + + :param authorization: The Authorization HTTP request header - return InsightsUserRolesInstance( + :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({}) + + 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 @@ -133,21 +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, ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return InsightsUserRolesInstance( + :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 = InsightsUserRolesInstance( self._version, payload, ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -160,6 +252,7 @@ def __repr__(self) -> str: class InsightsUserRolesList(ListResource): + def __init__(self, version: Version): """ Initialize the InsightsUserRolesList diff --git a/twilio/rest/flex_api/v1/interaction/__init__.py b/twilio/rest/flex_api/v1/interaction/__init__.py index 852b29c5e5..9e63203161 100644 --- a/twilio/rest/flex_api/v1/interaction/__init__.py +++ b/twilio/rest/flex_api/v1/interaction/__init__.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - -from typing import Any, Dict, Optional +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 @@ -26,13 +26,14 @@ class InteractionInstance(InstanceResource): - """ :ivar sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. :ivar channel: A JSON object that defines the Interaction’s communication channel and includes details about the channel. See the [Outbound SMS](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) and [inbound (API-initiated)](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#api-initiated-contact) Channel object examples. :ivar routing: A JSON Object representing the routing rules for the Interaction Channel. See [Outbound SMS Example](https://www.twilio.com/docs/flex/developer/conversations/interactions-api/interactions#agent-initiated-outbound-interactions) for an example Routing object. The Interactions resource uses TaskRouter for all routing functionality. All attributes in the Routing object on your Interaction request body are added “as is” to the task. For a list of known attributes consumed by the Flex UI and/or Flex Insights, see [Known Task Attributes](https://www.twilio.com/docs/flex/developer/conversations/interactions-api#task-attributes). :ivar url: :ivar links: + :ivar interaction_context_sid: + :ivar webhook_ttid: """ def __init__( @@ -45,10 +46,15 @@ def __init__( self.routing: Optional[Dict[str, object]] = payload.get("routing") self.url: Optional[str] = payload.get("url") self.links: Optional[Dict[str, object]] = payload.get("links") + 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 @@ -84,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: """ @@ -102,6 +182,7 @@ def __repr__(self) -> str: class InteractionContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the InteractionContext @@ -119,6 +200,22 @@ def __init__(self, version: Version, sid: str): self._channels: Optional[InteractionChannelList] = None + 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) -> InteractionInstance: """ Fetch the InteractionInstance @@ -126,17 +223,43 @@ def fetch(self) -> InteractionInstance: :returns: The fetched InteractionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return InteractionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> InteractionInstance: """ @@ -145,17 +268,135 @@ async def fetch_async(self) -> InteractionInstance: :returns: The fetched InteractionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return InteractionInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return InteractionInstance( + 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: @@ -180,6 +421,7 @@ def __repr__(self) -> str: class InteractionList(ListResource): + def __init__(self, version: Version): """ Initialize the InteractionList @@ -191,56 +433,172 @@ def __init__(self, version: Version): self._uri = "/Interactions" - def create(self, channel: object, routing: object) -> InteractionInstance: + 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, + ) -> tuple: """ - Create the InteractionInstance + Internal helper for create operation - :param channel: The Interaction's channel. - :param routing: The Interaction's routing logic. - - :returns: The created InteractionInstance + 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"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return InteractionInstance(self._version, payload) + headers["Accept"] = "application/json" - async def create_async( - self, channel: object, routing: object + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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"}) + + 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, + 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 939e587cf7..2c362c9dbd 100644 --- a/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py +++ b/twilio/rest/flex_api/v1/interaction/interaction_channel/__init__.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - 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 @@ -26,18 +26,21 @@ 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): + class ChannelStatus(object): SETUP = "setup" ACTIVE = "active" FAILED = "failed" CLOSED = "closed" - - class Status(object): - CLOSED = "closed" - WRAPUP = "wrapup" + INACTIVE = "inactive" + PAUSE = "pause" + TRANSFER = "transfer" class Type(object): VOICE = "voice" @@ -49,6 +52,10 @@ class Type(object): MESSENGER = "messenger" GBM = "gbm" + class UpdateChannelStatus(object): + CLOSED = "closed" + INACTIVE = "inactive" + """ :ivar sid: The unique string created by Twilio to identify an Interaction Channel resource, prefixed with UO. :ivar interaction_sid: The unique string created by Twilio to identify an Interaction resource, prefixed with KD. @@ -84,6 +91,7 @@ def __init__( "interaction_sid": interaction_sid, "sid": sid or self.sid, } + self._context: Optional[InteractionChannelContext] = None @property @@ -120,16 +128,34 @@ 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.Status", + status: "InteractionChannelInstance.UpdateChannelStatus", routing: Union[object, object] = values.unset, ) -> "InteractionChannelInstance": """ Update the InteractionChannelInstance :param status: - :param routing: Optional. The state of associated tasks. If not specified, all tasks will be set to `wrapping`. + :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 """ @@ -140,14 +166,14 @@ def update( async def update_async( self, - status: "InteractionChannelInstance.Status", + status: "InteractionChannelInstance.UpdateChannelStatus", routing: Union[object, object] = values.unset, ) -> "InteractionChannelInstance": """ Asynchronous coroutine to update the InteractionChannelInstance :param status: - :param routing: Optional. The state of associated tasks. If not specified, all tasks will be set to `wrapping`. + :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 """ @@ -156,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: """ @@ -170,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 @@ -181,6 +250,7 @@ def __repr__(self) -> str: class InteractionChannelContext(InstanceContext): + def __init__(self, version: Version, interaction_sid: str, sid: str): """ Initialize the InteractionChannelContext @@ -202,6 +272,23 @@ 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) -> 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) -> InteractionChannelInstance: """ @@ -210,18 +297,45 @@ def fetch(self) -> InteractionChannelInstance: :returns: The fetched InteractionChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], ) - return InteractionChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> InteractionChannelInstance: """ @@ -230,45 +344,72 @@ async def fetch_async(self) -> InteractionChannelInstance: :returns: The fetched InteractionChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return InteractionChannelInstance( + self._version, + payload, + interaction_sid=self._solution["interaction_sid"], + sid=self._solution["sid"], ) - return InteractionChannelInstance( + 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( + def _update( self, - status: "InteractionChannelInstance.Status", + status: "InteractionChannelInstance.UpdateChannelStatus", routing: Union[object, object] = values.unset, - ) -> InteractionChannelInstance: + ) -> tuple: """ - Update the InteractionChannelInstance - - :param status: - :param routing: Optional. The state of associated tasks. If not specified, all tasks will be set to `wrapping`. + Internal helper for update operation - :returns: The updated InteractionChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Status": status, "Routing": serialize.object(routing), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -276,32 +417,70 @@ def update( sid=self._solution["sid"], ) - async def update_async( + def update_with_http_info( self, - status: "InteractionChannelInstance.Status", + 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: Optional. The state of associated tasks. If not specified, all tasks will be set to `wrapping`. + :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( { "Status": status, "Routing": serialize.object(routing), } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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: "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, @@ -309,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: """ @@ -335,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 @@ -346,12 +562,14 @@ def __repr__(self) -> str: class InteractionChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInstance: """ Build an instance of InteractionChannelInstance :param payload: Payload response from the API """ + return InteractionChannelInstance( self._version, payload, interaction_sid=self._solution["interaction_sid"] ) @@ -366,6 +584,7 @@ def __repr__(self) -> str: class InteractionChannelList(ListResource): + def __init__(self, version: Version, interaction_sid: str): """ Initialize the InteractionChannelList @@ -432,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, @@ -451,6 +720,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -477,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( @@ -485,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, @@ -509,8 +830,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return InteractionChannelPage(self._version, response, self._solution) + 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 InteractionChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -536,10 +863,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return InteractionChannelPage(self._version, response, self._solution) + 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: """ @@ -551,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: """ @@ -563,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 b585176ec9..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 @@ -12,9 +12,9 @@ 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.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,7 +23,6 @@ class InteractionChannelInviteInstance(InstanceResource): - """ :ivar sid: The unique string created by Twilio to identify an Interaction Channel Invite resource. :ivar interaction_sid: The Interaction SID for this Channel. @@ -63,12 +62,14 @@ def __repr__(self) -> str: class InteractionChannelInvitePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InteractionChannelInviteInstance: """ Build an instance of InteractionChannelInviteInstance :param payload: Payload response from the API """ + return InteractionChannelInviteInstance( self._version, payload, @@ -86,6 +87,7 @@ def __repr__(self) -> str: class InteractionChannelInviteList(ListResource): + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): """ Initialize the InteractionChannelInviteList @@ -108,26 +110,38 @@ 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 - - :param routing: The Interaction's routing logic. + Internal helper for create operation - :returns: The created InteractionChannelInviteInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Routing": serialize.object(routing), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -135,26 +149,55 @@ 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( { "Routing": serialize.object(routing), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -162,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, @@ -212,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, @@ -231,6 +341,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -257,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( @@ -265,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, @@ -289,8 +451,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return InteractionChannelInvitePage(self._version, response, self._solution) + 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 InteractionChannelInvitePage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -316,10 +486,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return InteractionChannelInvitePage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -331,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: """ @@ -343,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 761516f9fa..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 @@ -12,9 +12,9 @@ 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.api_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 +23,7 @@ class InteractionChannelParticipantInstance(InstanceResource): + class Status(object): CLOSED = "closed" WRAPUP = "wrapup" @@ -40,6 +41,7 @@ class Type(object): :ivar interaction_sid: The Interaction Sid for this channel. :ivar channel_sid: The Channel Sid for this Participant. :ivar url: + :ivar routing_properties: The Participant's routing properties. """ def __init__( @@ -59,12 +61,16 @@ def __init__( self.interaction_sid: Optional[str] = payload.get("interaction_sid") self.channel_sid: Optional[str] = payload.get("channel_sid") self.url: Optional[str] = payload.get("url") + self.routing_properties: Optional[Dict[str, object]] = payload.get( + "routing_properties" + ) self._solution = { "interaction_sid": interaction_sid, "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InteractionChannelParticipantContext] = None @property @@ -112,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 @@ -125,6 +159,7 @@ def __repr__(self) -> str: class InteractionChannelParticipantContext(InstanceContext): + def __init__( self, version: Version, interaction_sid: str, channel_sid: str, sid: str ): @@ -148,28 +183,40 @@ 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( { "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -178,28 +225,62 @@ 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( { "Status": status, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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: "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, @@ -208,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 @@ -221,6 +322,7 @@ def __repr__(self) -> str: class InteractionChannelParticipantPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> InteractionChannelParticipantInstance: @@ -229,6 +331,7 @@ def get_instance( :param payload: Payload response from the API """ + return InteractionChannelParticipantInstance( self._version, payload, @@ -246,6 +349,7 @@ def __repr__(self) -> str: class InteractionChannelParticipantList(ListResource): + def __init__(self, version: Version, interaction_sid: str, channel_sid: str): """ Initialize the InteractionChannelParticipantList @@ -266,32 +370,56 @@ def __init__(self, version: Version, interaction_sid: str, channel_sid: str): **self._solution ) - def create( + def _create( self, type: "InteractionChannelParticipantInstance.Type", media_properties: object, - ) -> InteractionChannelParticipantInstance: + routing_properties: Union[object, object] = values.unset, + ) -> tuple: """ - Create the InteractionChannelParticipantInstance + Internal helper for create operation - :param type: - :param media_properties: JSON representing the Media Properties for the new Participant. - - :returns: The created InteractionChannelParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Type": type, "MediaProperties": serialize.object(media_properties), + "RoutingProperties": serialize.object(routing_properties), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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: "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, @@ -299,32 +427,84 @@ def create( channel_sid=self._solution["channel_sid"], ) - async def create_async( + def create_with_http_info( self, type: "InteractionChannelParticipantInstance.Type", media_properties: object, - ) -> InteractionChannelParticipantInstance: + routing_properties: Union[object, object] = values.unset, + ) -> 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( { "Type": type, "MediaProperties": serialize.object(media_properties), + "RoutingProperties": serialize.object(routing_properties), } ) + 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, + 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, @@ -332,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, @@ -382,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, @@ -401,6 +659,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -427,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( @@ -435,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, @@ -459,9 +769,15 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 InteractionChannelParticipantPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -488,12 +804,90 @@ async def page_async( } ) + 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 + 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: """ @@ -506,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( @@ -522,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 new file mode 100644 index 0000000000..5765f3478d --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin/__init__.py @@ -0,0 +1,1206 @@ +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, 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.flex_api.v1.plugin.plugin_versions import PluginVersionsList + + +class PluginInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin resource and owns this resource. + :ivar unique_name: The name that uniquely identifies this Flex Plugin resource. + :ivar friendly_name: The friendly name this Flex Plugin resource. + :ivar description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + :ivar archived: Whether the Flex Plugin is archived. The default value is false. + :ivar date_created: The date and time in GMT-7 when the Flex Plugin was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar date_updated: The date and time in GMT-7 when the Flex Plugin was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin 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.unique_name: Optional[str] = payload.get("unique_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + 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[PluginContext] = None + + @property + def _proxy(self) -> "PluginContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginContext for this PluginInstance + """ + if self._context is None: + self._context = PluginContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginInstance": + """ + Fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginInstance": + """ + Asynchronous coroutine to fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + return await self._proxy.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, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> "PluginInstance": + """ + 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 + """ + return self._proxy.update( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + description=description, + ) + + 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 + """ + return await self._proxy.update_async( + flex_metadata=flex_metadata, + friendly_name=friendly_name, + 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: + """ + Access the plugin_versions + """ + return self._proxy.plugin_versions + + 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 PluginContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Plugins/{sid}".format(**self._solution) + + 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 + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginInstance 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._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 + ) -> PluginInstance: + """ + Asynchronous coroutine to fetch the PluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginInstance + """ + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + 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 + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata + ) + instance = PluginInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + def _update( + self, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Description": description, + } + ) + 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["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, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + 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, _, _ = 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( + { + "FriendlyName": friendly_name, + "Description": description, + } + ) + 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["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, + 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: + """ + Access the plugin_versions + """ + if self._plugin_versions is None: + self._plugin_versions = PluginVersionsList( + self._version, + self._solution["sid"], + ) + return self._plugin_versions + + 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 PluginPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginInstance: + """ + Build an instance of PluginInstance + + :param payload: Payload response from the API + """ + + return PluginInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PluginList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PluginService/Plugins" + + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "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, + unique_name: str, + flex_metadata: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginInstance: + """ + 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, _, _ = 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( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "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, + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginInstance]: + """ + Streams PluginInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginInstance]: + """ + Asynchronously streams PluginInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginInstance]: + """ + Lists PluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginInstance]: + """ + Asynchronously lists PluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + 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, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginPage: + """ + Retrieve a single page of PluginInstance records from the API. + Request is executed immediately + + :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: Page of PluginInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginPage(self._version, response) + + async def page_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, + ) -> PluginPage: + """ + Asynchronously retrieve a single page of PluginInstance records from the API. + Request is executed immediately + + :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: Page of PluginInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PluginPage: + """ + Asynchronously retrieve a specific page of PluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginPage(self._version, response) + + def get(self, sid: str) -> PluginContext: + """ + Constructs a PluginContext + + :param sid: The SID of the Flex Plugin resource to update. + """ + return PluginContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginContext: + """ + Constructs a PluginContext + + :param sid: The SID of the Flex Plugin resource to update. + """ + return PluginContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/plugin/plugin_versions.py b/twilio/rest/flex_api/v1/plugin/plugin_versions.py new file mode 100644 index 0000000000..acd3330caa --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin/plugin_versions.py @@ -0,0 +1,1025 @@ +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, 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 PluginVersionsInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Version resource. + :ivar plugin_sid: The SID of the Flex Plugin resource this Flex Plugin Version belongs to. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Version resource and owns this resource. + :ivar version: The unique version of this Flex Plugin Version. + :ivar plugin_url: The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + :ivar changelog: A changelog that describes the changes this Flex Plugin Version brings. + :ivar private: Whether the Flex Plugin Version is validated. The default value is false. + :ivar archived: Whether the Flex Plugin Version is archived. The default value is false. + :ivar validated: + :ivar date_created: The date and time in GMT when the Flex Plugin Version was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Version resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + plugin_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.plugin_sid: Optional[str] = payload.get("plugin_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.version: Optional[str] = payload.get("version") + self.plugin_url: Optional[str] = payload.get("plugin_url") + self.changelog: Optional[str] = payload.get("changelog") + self.private: Optional[bool] = payload.get("private") + self.archived: Optional[bool] = payload.get("archived") + self.validated: Optional[bool] = payload.get("validated") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "plugin_sid": plugin_sid, + "sid": sid or self.sid, + } + + self._context: Optional[PluginVersionsContext] = None + + @property + def _proxy(self) -> "PluginVersionsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginVersionsContext for this PluginVersionsInstance + """ + if self._context is None: + self._context = PluginVersionsContext( + self._version, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionsInstance": + """ + Fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginVersionsInstance": + """ + Asynchronous coroutine to fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + return await self._proxy.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginVersionsContext(InstanceContext): + + def __init__(self, version: Version, plugin_sid: str, sid: str): + """ + Initialize the PluginVersionsContext + + :param version: Version that contains the resource + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "plugin_sid": plugin_sid, + "sid": sid, + } + self._uri = "/PluginService/Plugins/{plugin_sid}/Versions/{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 + ) -> PluginVersionsInstance: + """ + Fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginVersionsInstance 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._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 + ) -> PluginVersionsInstance: + """ + Asynchronous coroutine to fetch the PluginVersionsInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginVersionsInstance + """ + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginVersionsInstance( + self._version, + payload, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + 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 + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + 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) + + 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 PluginVersionsPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginVersionsInstance: + """ + Build an instance of PluginVersionsInstance + + :param payload: Payload response from the API + """ + + return PluginVersionsInstance( + self._version, payload, plugin_sid=self._solution["plugin_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PluginVersionsList(ListResource): + + def __init__(self, version: Version, plugin_sid: str): + """ + Initialize the PluginVersionsList + + :param version: Version that contains the resource + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "plugin_sid": plugin_sid, + } + self._uri = "/PluginService/Plugins/{plugin_sid}/Versions".format( + **self._solution + ) + + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Version": resource_version, + "PluginUrl": plugin_url, + "Changelog": changelog, + "Private": serialize.boolean_to_string(private), + "CliVersion": cli_version, + "ValidateStatus": validate_status, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "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, + 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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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": resource_version, + "PluginUrl": plugin_url, + "Changelog": changelog, + "Private": serialize.boolean_to_string(private), + "CliVersion": cli_version, + "ValidateStatus": validate_status, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "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, + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginVersionsInstance]: + """ + Streams PluginVersionsInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginVersionsInstance]: + """ + Asynchronously streams PluginVersionsInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginVersionsInstance]: + """ + Lists PluginVersionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginVersionsInstance]: + """ + Asynchronously lists PluginVersionsInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + 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, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginVersionsPage: + """ + Retrieve a single page of PluginVersionsInstance records from the API. + Request is executed immediately + + :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: Page of PluginVersionsInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginVersionsPage(self._version, response, solution=self._solution) + + async def page_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, + ) -> PluginVersionsPage: + """ + Asynchronously retrieve a single page of PluginVersionsInstance records from the API. + Request is executed immediately + + :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: Page of PluginVersionsInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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: + """ + Retrieve a specific page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginVersionsInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginVersionsPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> PluginVersionsPage: + """ + Asynchronously retrieve a specific page of PluginVersionsInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginVersionsInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginVersionsPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> PluginVersionsContext: + """ + Constructs a PluginVersionsContext + + :param sid: The SID of the Flex Plugin Version resource to fetch. + """ + return PluginVersionsContext( + self._version, plugin_sid=self._solution["plugin_sid"], sid=sid + ) + + def __call__(self, sid: str) -> PluginVersionsContext: + """ + Constructs a PluginVersionsContext + + :param sid: The SID of the Flex Plugin Version resource to fetch. + """ + return PluginVersionsContext( + self._version, plugin_sid=self._solution["plugin_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_archive.py b/twilio/rest/flex_api/v1/plugin_archive.py new file mode 100644 index 0000000000..7dbb89ffdc --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_archive.py @@ -0,0 +1,312 @@ +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 PluginArchiveInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin resource and owns this resource. + :ivar unique_name: The name that uniquely identifies this Flex Plugin resource. + :ivar friendly_name: The friendly name this Flex Plugin resource. + :ivar description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + :ivar archived: Whether the Flex Plugin is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin 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 Flex Plugin was last updated specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin 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.account_sid: Optional[str] = payload.get("account_sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + 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 = { + "sid": sid or self.sid, + } + + self._context: Optional[PluginArchiveContext] = None + + @property + def _proxy(self) -> "PluginArchiveContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginArchiveContext for this PluginArchiveInstance + """ + if self._context is None: + self._context = PluginArchiveContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginArchiveInstance": + """ + Update the PluginArchiveInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The updated PluginArchiveInstance + """ + return self._proxy.update( + flex_metadata=flex_metadata, + ) + + 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 + """ + return await self._proxy.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginArchiveContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginArchiveContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin resource to archive. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Plugins/{sid}/Archive".format(**self._solution) + + def _update(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + 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.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def update( + self, flex_metadata: Union[str, object] = values.unset + ) -> 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({}) + + 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.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginArchiveList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginArchiveList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> PluginArchiveContext: + """ + Constructs a PluginArchiveContext + + :param sid: The SID of the Flex Plugin resource to archive. + """ + return PluginArchiveContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginArchiveContext: + """ + Constructs a PluginArchiveContext + + :param sid: The SID of the Flex Plugin resource to archive. + """ + return PluginArchiveContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/plugin_configuration/__init__.py b/twilio/rest/flex_api/v1/plugin_configuration/__init__.py new file mode 100644 index 0000000000..d98e1f3615 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_configuration/__init__.py @@ -0,0 +1,960 @@ +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, 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.flex_api.v1.plugin_configuration.configured_plugin import ( + ConfiguredPluginList, +) + + +class PluginConfigurationInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Configuration resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Configuration resource and owns this resource. + :ivar name: The name of this Flex Plugin Configuration. + :ivar description: The description of the Flex Plugin Configuration resource. + :ivar archived: Whether the Flex Plugin Configuration is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin Configuration was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Configuration 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.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + 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[PluginConfigurationContext] = None + + @property + def _proxy(self) -> "PluginConfigurationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginConfigurationContext for this PluginConfigurationInstance + """ + if self._context is None: + self._context = PluginConfigurationContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationInstance": + """ + Fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginConfigurationInstance": + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + return await self._proxy.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: + """ + Access the plugins + """ + return self._proxy.plugins + + 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 PluginConfigurationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginConfigurationContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin Configuration resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Configurations/{sid}".format(**self._solution) + + 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: + """ + Fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginConfigurationInstance 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._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 + ) -> PluginConfigurationInstance: + """ + Asynchronous coroutine to fetch the PluginConfigurationInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginConfigurationInstance + """ + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + 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 + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata + ) + instance = PluginConfigurationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def plugins(self) -> ConfiguredPluginList: + """ + Access the plugins + """ + if self._plugins is None: + self._plugins = ConfiguredPluginList( + self._version, + self._solution["sid"], + ) + return self._plugins + + 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 PluginConfigurationPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginConfigurationInstance: + """ + Build an instance of PluginConfigurationInstance + + :param payload: Payload response from the API + """ + + return PluginConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PluginConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PluginService/Configurations" + + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Name": name, + "Plugins": serialize.map(plugins, lambda e: serialize.object(e)), + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "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: str, + flex_metadata: Union[str, object] = values.unset, + plugins: Union[List[object], object] = values.unset, + description: Union[str, object] = values.unset, + ) -> PluginConfigurationInstance: + """ + 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, _, _ = 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( + { + "Name": name, + "Plugins": serialize.map(plugins, lambda e: serialize.object(e)), + "Description": description, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "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: 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginConfigurationInstance]: + """ + Streams PluginConfigurationInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginConfigurationInstance]: + """ + Asynchronously streams PluginConfigurationInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginConfigurationInstance]: + """ + Lists PluginConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginConfigurationInstance]: + """ + Asynchronously lists PluginConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + 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, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginConfigurationPage: + """ + Retrieve a single page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :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: Page of PluginConfigurationInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginConfigurationPage(self._version, response) + + async def page_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, + ) -> PluginConfigurationPage: + """ + Asynchronously retrieve a single page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :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: Page of PluginConfigurationInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PluginConfigurationPage: + """ + Asynchronously retrieve a specific page of PluginConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginConfigurationPage(self._version, response) + + def get(self, sid: str) -> PluginConfigurationContext: + """ + Constructs a PluginConfigurationContext + + :param sid: The SID of the Flex Plugin Configuration resource to fetch. + """ + return PluginConfigurationContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginConfigurationContext: + """ + Constructs a PluginConfigurationContext + + :param sid: The SID of the Flex Plugin Configuration resource to fetch. + """ + return PluginConfigurationContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py b/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py new file mode 100644 index 0000000000..473f86f966 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_configuration/configured_plugin.py @@ -0,0 +1,813 @@ +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, 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 ConfiguredPluginInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Flex Plugin resource is installed for. + :ivar configuration_sid: The SID of the Flex Plugin Configuration that this Flex Plugin belongs to. + :ivar plugin_sid: The SID of the Flex Plugin. + :ivar plugin_version_sid: The SID of the Flex Plugin Version. + :ivar phase: The phase this Flex Plugin would initialize at runtime. + :ivar plugin_url: The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + :ivar unique_name: The name that uniquely identifies this Flex Plugin resource. + :ivar friendly_name: The friendly name of this Flex Plugin resource. + :ivar description: A descriptive string that you create to describe the plugin resource. It can be up to 500 characters long + :ivar plugin_archived: Whether the Flex Plugin is archived. The default value is false. + :ivar version: The latest version of this Flex Plugin Version. + :ivar changelog: A changelog that describes the changes this Flex Plugin Version brings. + :ivar plugin_version_archived: Whether the Flex Plugin Version is archived. The default value is false. + :ivar private: Whether to validate the request is authorized to access the Flex Plugin Version. + :ivar date_created: The date and time in GMT when the Flex Plugin was installed specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + configuration_sid: str, + plugin_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.configuration_sid: Optional[str] = payload.get("configuration_sid") + self.plugin_sid: Optional[str] = payload.get("plugin_sid") + self.plugin_version_sid: Optional[str] = payload.get("plugin_version_sid") + self.phase: Optional[int] = deserialize.integer(payload.get("phase")) + self.plugin_url: Optional[str] = payload.get("plugin_url") + self.unique_name: Optional[str] = payload.get("unique_name") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.plugin_archived: Optional[bool] = payload.get("plugin_archived") + self.version: Optional[str] = payload.get("version") + self.changelog: Optional[str] = payload.get("changelog") + self.plugin_version_archived: Optional[bool] = payload.get( + "plugin_version_archived" + ) + self.private: Optional[bool] = payload.get("private") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "configuration_sid": configuration_sid, + "plugin_sid": plugin_sid or self.plugin_sid, + } + + self._context: Optional[ConfiguredPluginContext] = None + + @property + def _proxy(self) -> "ConfiguredPluginContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ConfiguredPluginContext for this ConfiguredPluginInstance + """ + if self._context is None: + self._context = ConfiguredPluginContext( + self._version, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "ConfiguredPluginInstance": + """ + Fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "ConfiguredPluginInstance": + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + return await self._proxy.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ConfiguredPluginContext(InstanceContext): + + def __init__(self, version: Version, configuration_sid: str, plugin_sid: str): + """ + Initialize the ConfiguredPluginContext + + :param version: Version that contains the resource + :param configuration_sid: The SID of the Flex Plugin Configuration the resource to belongs to. + :param plugin_sid: The unique string that we created to identify the Flex Plugin resource. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "configuration_sid": configuration_sid, + "plugin_sid": plugin_sid, + } + self._uri = "/PluginService/Configurations/{configuration_sid}/Plugins/{plugin_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 + ) -> ConfiguredPluginInstance: + """ + Fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=self._solution["plugin_sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the ConfiguredPluginInstance 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._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 + ) -> ConfiguredPluginInstance: + """ + Asynchronous coroutine to fetch the ConfiguredPluginInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched ConfiguredPluginInstance + """ + 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"], + ) + + 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 + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + 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) + + 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 ConfiguredPluginPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ConfiguredPluginInstance: + """ + Build an instance of ConfiguredPluginInstance + + :param payload: Payload response from the API + """ + + return ConfiguredPluginInstance( + self._version, + payload, + configuration_sid=self._solution["configuration_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ConfiguredPluginList(ListResource): + + def __init__(self, version: Version, configuration_sid: str): + """ + Initialize the ConfiguredPluginList + + :param version: Version that contains the resource + :param configuration_sid: The SID of the Flex Plugin Configuration the resource to belongs to. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "configuration_sid": configuration_sid, + } + self._uri = "/PluginService/Configurations/{configuration_sid}/Plugins".format( + **self._solution + ) + + def stream( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[ConfiguredPluginInstance]: + """ + Streams ConfiguredPluginInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[ConfiguredPluginInstance]: + """ + Asynchronously streams ConfiguredPluginInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfiguredPluginInstance]: + """ + Lists ConfiguredPluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[ConfiguredPluginInstance]: + """ + Asynchronously lists ConfiguredPluginInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + 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, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ConfiguredPluginPage: + """ + Retrieve a single page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :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: Page of ConfiguredPluginInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConfiguredPluginPage(self._version, response, solution=self._solution) + + async def page_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, + ) -> ConfiguredPluginPage: + """ + Asynchronously retrieve a single page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :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: Page of ConfiguredPluginInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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: + """ + Retrieve a specific page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfiguredPluginInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ConfiguredPluginPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ConfiguredPluginPage: + """ + Asynchronously retrieve a specific page of ConfiguredPluginInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ConfiguredPluginInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ConfiguredPluginPage(self._version, response, solution=self._solution) + + def get(self, plugin_sid: str) -> ConfiguredPluginContext: + """ + Constructs a ConfiguredPluginContext + + :param plugin_sid: The unique string that we created to identify the Flex Plugin resource. + """ + return ConfiguredPluginContext( + self._version, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=plugin_sid, + ) + + def __call__(self, plugin_sid: str) -> ConfiguredPluginContext: + """ + Constructs a ConfiguredPluginContext + + :param plugin_sid: The unique string that we created to identify the Flex Plugin resource. + """ + return ConfiguredPluginContext( + self._version, + configuration_sid=self._solution["configuration_sid"], + plugin_sid=plugin_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/plugin_configuration_archive.py b/twilio/rest/flex_api/v1/plugin_configuration_archive.py new file mode 100644 index 0000000000..e880c68ec4 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_configuration_archive.py @@ -0,0 +1,316 @@ +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 PluginConfigurationArchiveInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Configuration resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Configuration resource and owns this resource. + :ivar name: The name of this Flex Plugin Configuration. + :ivar description: The description of the Flex Plugin Configuration resource. + :ivar archived: Whether the Flex Plugin Configuration is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin Configuration was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Configuration 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.account_sid: Optional[str] = payload.get("account_sid") + self.name: Optional[str] = payload.get("name") + self.description: Optional[str] = payload.get("description") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[PluginConfigurationArchiveContext] = None + + @property + def _proxy(self) -> "PluginConfigurationArchiveContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginConfigurationArchiveContext for this PluginConfigurationArchiveInstance + """ + if self._context is None: + self._context = PluginConfigurationArchiveContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + 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 + """ + return self._proxy.update( + flex_metadata=flex_metadata, + ) + + 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 + """ + return await self._proxy.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class PluginConfigurationArchiveContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginConfigurationArchiveContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin Configuration resource to archive. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/PluginService/Configurations/{sid}/Archive".format( + **self._solution + ) + + def _update(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + 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.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"] + ) + + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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({}) + 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.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class PluginConfigurationArchiveList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginConfigurationArchiveList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> PluginConfigurationArchiveContext: + """ + Constructs a PluginConfigurationArchiveContext + + :param sid: The SID of the Flex Plugin Configuration resource to archive. + """ + return PluginConfigurationArchiveContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginConfigurationArchiveContext: + """ + Constructs a PluginConfigurationArchiveContext + + :param sid: The SID of the Flex Plugin Configuration resource to archive. + """ + return PluginConfigurationArchiveContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/plugin_release.py b/twilio/rest/flex_api/v1/plugin_release.py new file mode 100644 index 0000000000..08d3bbd00f --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_release.py @@ -0,0 +1,882 @@ +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, 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 PluginReleaseInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Plugin Release resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Plugin Release resource and owns this resource. + :ivar configuration_sid: The SID of the Plugin Configuration resource to release. + :ivar date_created: The date and time in GMT when the Flex Plugin Release was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Plugin Release 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.account_sid: Optional[str] = payload.get("account_sid") + self.configuration_sid: Optional[str] = payload.get("configuration_sid") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[PluginReleaseContext] = None + + @property + def _proxy(self) -> "PluginReleaseContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginReleaseContext for this PluginReleaseInstance + """ + if self._context is None: + self._context = PluginReleaseContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginReleaseInstance": + """ + Fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + return self._proxy.fetch( + flex_metadata=flex_metadata, + ) + + async def fetch_async( + self, flex_metadata: Union[str, object] = values.unset + ) -> "PluginReleaseInstance": + """ + Asynchronous coroutine to fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + return await self._proxy.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginReleaseContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PluginReleaseContext + + :param version: Version that contains the resource + :param sid: The SID of the Flex Plugin Release resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + 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: + """ + Fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + payload, _, _ = self._fetch(flex_metadata=flex_metadata) + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the PluginReleaseInstance 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._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 + ) -> PluginReleaseInstance: + """ + Asynchronous coroutine to fetch the PluginReleaseInstance + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: The fetched PluginReleaseInstance + """ + payload, _, _ = await self._fetch_async(flex_metadata=flex_metadata) + return PluginReleaseInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + 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 + + :param flex_metadata: The Flex-Metadata HTTP request header + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._fetch_async( + flex_metadata=flex_metadata + ) + instance = PluginReleaseInstance( + 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 PluginReleasePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PluginReleaseInstance: + """ + Build an instance of PluginReleaseInstance + + :param payload: Payload response from the API + """ + + return PluginReleaseInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PluginReleaseList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginReleaseList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/PluginService/Releases" + + def _create( + self, configuration_id: str, flex_metadata: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ConfigurationId": configuration_id, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "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_id: str, flex_metadata: Union[str, object] = values.unset + ) -> 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( + { + "ConfigurationId": configuration_id, + } + ) + headers = values.of( + { + "Flex-Metadata": flex_metadata, + "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_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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PluginReleaseInstance]: + """ + Streams PluginReleaseInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(flex_metadata=flex_metadata, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[PluginReleaseInstance]: + """ + Asynchronously streams PluginReleaseInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + flex_metadata=flex_metadata, page_size=limits["page_size"] + ) + + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginReleaseInstance]: + """ + Lists PluginReleaseInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + flex_metadata: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PluginReleaseInstance]: + """ + Asynchronously lists PluginReleaseInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + flex_metadata=flex_metadata, + limit=limit, + page_size=page_size, + ) + ] + + 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, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> PluginReleasePage: + """ + Retrieve a single page of PluginReleaseInstance records from the API. + Request is executed immediately + + :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: Page of PluginReleaseInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PluginReleasePage(self._version, response) + + async def page_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, + ) -> PluginReleasePage: + """ + Asynchronously retrieve a single page of PluginReleaseInstance records from the API. + Request is executed immediately + + :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: Page of PluginReleaseInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginReleaseInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PluginReleasePage(self._version, response) + + async def get_page_async(self, target_url: str) -> PluginReleasePage: + """ + Asynchronously retrieve a specific page of PluginReleaseInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PluginReleaseInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PluginReleasePage(self._version, response) + + def get(self, sid: str) -> PluginReleaseContext: + """ + Constructs a PluginReleaseContext + + :param sid: The SID of the Flex Plugin Release resource to fetch. + """ + return PluginReleaseContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PluginReleaseContext: + """ + Constructs a PluginReleaseContext + + :param sid: The SID of the Flex Plugin Release resource to fetch. + """ + return PluginReleaseContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/plugin_version_archive.py b/twilio/rest/flex_api/v1/plugin_version_archive.py new file mode 100644 index 0000000000..d2b601a828 --- /dev/null +++ b/twilio/rest/flex_api/v1/plugin_version_archive.py @@ -0,0 +1,344 @@ +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 PluginVersionArchiveInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Flex Plugin Version resource. + :ivar plugin_sid: The SID of the Flex Plugin resource this Flex Plugin Version belongs to. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Flex Plugin Version resource and owns this resource. + :ivar version: The unique version of this Flex Plugin Version. + :ivar plugin_url: The URL of where the Flex Plugin Version JavaScript bundle is hosted on. + :ivar changelog: A changelog that describes the changes this Flex Plugin Version brings. + :ivar private: Whether to inject credentials while accessing this Plugin Version. The default value is false. + :ivar archived: Whether the Flex Plugin Version is archived. The default value is false. + :ivar date_created: The date and time in GMT when the Flex Plugin Version was created specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar url: The absolute URL of the Flex Plugin Version resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + plugin_sid: Optional[str] = None, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.plugin_sid: Optional[str] = payload.get("plugin_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.version: Optional[str] = payload.get("version") + self.plugin_url: Optional[str] = payload.get("plugin_url") + self.changelog: Optional[str] = payload.get("changelog") + self.private: Optional[bool] = payload.get("private") + self.archived: Optional[bool] = payload.get("archived") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "plugin_sid": plugin_sid or self.plugin_sid, + "sid": sid or self.sid, + } + + self._context: Optional[PluginVersionArchiveContext] = None + + @property + def _proxy(self) -> "PluginVersionArchiveContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PluginVersionArchiveContext for this PluginVersionArchiveInstance + """ + if self._context is None: + self._context = PluginVersionArchiveContext( + self._version, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + return self._context + + 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 + """ + return self._proxy.update( + flex_metadata=flex_metadata, + ) + + 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 + """ + return await self._proxy.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginVersionArchiveContext(InstanceContext): + + def __init__(self, version: Version, plugin_sid: str, sid: str): + """ + Initialize the PluginVersionArchiveContext + + :param version: Version that contains the resource + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to archive. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "plugin_sid": plugin_sid, + "sid": sid, + } + self._uri = "/PluginService/Plugins/{plugin_sid}/Versions/{sid}/Archive".format( + **self._solution + ) + + def _update(self, flex_metadata: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + 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.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, + plugin_sid=self._solution["plugin_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info( + self, flex_metadata: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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({}) + 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.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, + plugin_sid=self._solution["plugin_sid"], + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PluginVersionArchiveList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PluginVersionArchiveList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, plugin_sid: str, sid: str) -> PluginVersionArchiveContext: + """ + Constructs a PluginVersionArchiveContext + + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to archive. + """ + return PluginVersionArchiveContext( + self._version, plugin_sid=plugin_sid, sid=sid + ) + + def __call__(self, plugin_sid: str, sid: str) -> PluginVersionArchiveContext: + """ + Constructs a PluginVersionArchiveContext + + :param plugin_sid: The SID of the Flex Plugin the resource to belongs to. + :param sid: The SID of the Flex Plugin Version resource to archive. + """ + return PluginVersionArchiveContext( + self._version, plugin_sid=plugin_sid, sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/provisioning_status.py b/twilio/rest/flex_api/v1/provisioning_status.py new file mode 100644 index 0000000000..a13a1baab7 --- /dev/null +++ b/twilio/rest/flex_api/v1/provisioning_status.py @@ -0,0 +1,246 @@ +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 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 ProvisioningStatusInstance(InstanceResource): + + class Status(object): + ACTIVE = "active" + IN_PROGRESS = "in-progress" + NOT_CONFIGURED = "not-configured" + FAILED = "failed" + + """ + :ivar status: + :ivar url: The absolute URL of the resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.status: Optional["ProvisioningStatusInstance.Status"] = payload.get( + "status" + ) + self.url: Optional[str] = payload.get("url") + + self._context: Optional[ProvisioningStatusContext] = None + + @property + def _proxy(self) -> "ProvisioningStatusContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ProvisioningStatusContext for this ProvisioningStatusInstance + """ + if self._context is None: + self._context = ProvisioningStatusContext( + self._version, + ) + return self._context + + def fetch(self) -> "ProvisioningStatusInstance": + """ + Fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ProvisioningStatusInstance": + """ + Asynchronous coroutine to fetch the ProvisioningStatusInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + + return "" + + +class ProvisioningStatusContext(InstanceContext): + + def __init__(self, version: Version): + """ + Initialize the ProvisioningStatusContext + + :param version: Version that contains the resource + """ + super().__init__(version) + + self._uri = "/account/provision/status" + + 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) -> ProvisioningStatusInstance: + """ + Fetch the ProvisioningStatusInstance + + + :returns: The fetched ProvisioningStatusInstance + """ + payload, _, _ = self._fetch() + return ProvisioningStatusInstance( + self._version, + payload, + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ProvisioningStatusInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + + return "" + + +class ProvisioningStatusList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ProvisioningStatusList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self) -> ProvisioningStatusContext: + """ + Constructs a ProvisioningStatusContext + + """ + return ProvisioningStatusContext(self._version) + + def __call__(self) -> ProvisioningStatusContext: + """ + Constructs a ProvisioningStatusContext + + """ + return ProvisioningStatusContext(self._version) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v1/web_channel.py b/twilio/rest/flex_api/v1/web_channel.py index 436c0be8b2..0b0560cb89 100644 --- a/twilio/rest/flex_api/v1/web_channel.py +++ b/twilio/rest/flex_api/v1/web_channel.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class WebChannelInstance(InstanceResource): + class ChatStatus(object): INACTIVE = "inactive" @@ -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 @@ -155,6 +229,7 @@ def __repr__(self) -> str: class WebChannelContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the WebChannelContext @@ -170,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 @@ -177,9 +266,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -189,9 +300,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebChannelInstance 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) -> WebChannelInstance: @@ -201,17 +336,43 @@ def fetch(self) -> WebChannelInstance: :returns: The fetched WebChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return WebChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WebChannelInstance: """ @@ -220,17 +381,55 @@ async def fetch_async(self) -> WebChannelInstance: :returns: The fetched WebChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WebChannelInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return WebChannelInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ChatStatus": chat_status, + "PostEngagementData": post_engagement_data, + } + ) + 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, @@ -245,20 +444,57 @@ def update( :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( { "ChatStatus": chat_status, "PostEngagementData": post_engagement_data, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -273,20 +509,29 @@ async def update_async( :returns: The updated WebChannelInstance """ - data = values.of( - { - "ChatStatus": chat_status, - "PostEngagementData": post_engagement_data, - } + payload, _, _ = await self._update_async( + chat_status=chat_status, post_engagement_data=post_engagement_data ) + return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=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 and return response metadata - return WebChannelInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -299,12 +544,14 @@ def __repr__(self) -> str: class WebChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> WebChannelInstance: """ Build an instance of WebChannelInstance :param payload: Payload response from the API """ + return WebChannelInstance(self._version, payload) def __repr__(self) -> str: @@ -317,6 +564,7 @@ def __repr__(self) -> str: class WebChannelList(ListResource): + def __init__(self, version: Version): """ Initialize the WebChannelList @@ -328,6 +576,42 @@ def __init__(self, version: Version): self._uri = "/WebChannels" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FlexFlowSid": flex_flow_sid, + "Identity": identity, + "CustomerFriendlyName": customer_friendly_name, + "ChatFriendlyName": chat_friendly_name, + "ChatUniqueName": chat_unique_name, + "PreEngagementData": pre_engagement_data, + } + ) + 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, flex_flow_sid: str, @@ -349,6 +633,64 @@ def create( :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( { "FlexFlowSid": flex_flow_sid, @@ -359,14 +701,15 @@ def create( "PreEngagementData": pre_engagement_data, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WebChannelInstance(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, @@ -389,24 +732,47 @@ async def create_async( :returns: The created WebChannelInstance """ - data = values.of( - { - "FlexFlowSid": flex_flow_sid, - "Identity": identity, - "CustomerFriendlyName": customer_friendly_name, - "ChatFriendlyName": chat_friendly_name, - "ChatUniqueName": chat_unique_name, - "PreEngagementData": pre_engagement_data, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return WebChannelInstance(self._version, payload) + :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, @@ -458,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, @@ -477,6 +893,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -503,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( @@ -511,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, @@ -535,7 +1003,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 WebChannelPage(self._version, response) async def page_async( @@ -562,11 +1036,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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/__init__.py b/twilio/rest/flex_api/v2/__init__.py index e48012241d..e05ffcdfb5 100644 --- a/twilio/rest/flex_api/v2/__init__.py +++ b/twilio/rest/flex_api/v2/__init__.py @@ -15,10 +15,12 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain +from twilio.rest.flex_api.v2.flex_user import FlexUserList from twilio.rest.flex_api.v2.web_channels import WebChannelsList class V2(Version): + def __init__(self, domain: Domain): """ Initialize the V2 version of FlexApi @@ -26,8 +28,15 @@ def __init__(self, domain: Domain): :param domain: The Twilio.flex_api domain """ super().__init__(domain, "v2") + self._flex_user: Optional[FlexUserList] = None self._web_channels: Optional[WebChannelsList] = None + @property + def flex_user(self) -> FlexUserList: + if self._flex_user is None: + self._flex_user = FlexUserList(self) + return self._flex_user + @property def web_channels(self) -> WebChannelsList: if self._web_channels is None: diff --git a/twilio/rest/flex_api/v2/flex_user.py b/twilio/rest/flex_api/v2/flex_user.py new file mode 100644 index 0000000000..70ed7b7ac6 --- /dev/null +++ b/twilio/rest/flex_api/v2/flex_user.py @@ -0,0 +1,550 @@ +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, 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 FlexUserInstance(InstanceResource): + """ + :ivar account_sid: The unique SID of the account that created the resource. + :ivar instance_sid: The unique ID created by Twilio to identify a Flex instance. + :ivar user_sid: The unique SID identifier of the Twilio Unified User. + :ivar flex_user_sid: The unique SID identifier of the Flex User. + :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 username: Username of the User. + :ivar email: Email 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. + :ivar updated_date: The date that this user was updated, given in ISO 8601 format. + :ivar version: The current version of the user. + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + instance_sid: Optional[str] = None, + flex_user_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.instance_sid: Optional[str] = payload.get("instance_sid") + self.user_sid: Optional[str] = payload.get("user_sid") + self.flex_user_sid: Optional[str] = payload.get("flex_user_sid") + 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.username: Optional[str] = payload.get("username") + self.email: Optional[str] = payload.get("email") + self.locale: Optional[str] = payload.get("locale") + self.roles: Optional[List[str]] = payload.get("roles") + self.created_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("created_date") + ) + self.updated_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("updated_date") + ) + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "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 + def _proxy(self) -> "FlexUserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: FlexUserContext for this FlexUserInstance + """ + if self._context is None: + self._context = FlexUserContext( + self._version, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + return self._context + + def fetch(self) -> "FlexUserInstance": + """ + Fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "FlexUserInstance": + """ + Asynchronous coroutine to fetch the FlexUserInstance + + + :returns: The fetched 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, + 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 + """ + return self._proxy.update( + email=email, + user_sid=user_sid, + locale=locale, + ) + + 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 + """ + return await self._proxy.update_async( + email=email, + 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, + ) + + 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 FlexUserContext(InstanceContext): + + def __init__(self, version: Version, instance_sid: str, flex_user_sid: str): + """ + Initialize the FlexUserContext + + :param version: Version that contains the resource + :param instance_sid: The unique ID created by Twilio to identify a Flex instance. + :param flex_user_sid: The unique id for the flex user. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "instance_sid": instance_sid, + "flex_user_sid": flex_user_sid, + } + self._uri = "/Instances/{instance_sid}/Users/{flex_user_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) -> FlexUserInstance: + """ + Fetch the FlexUserInstance + + + :returns: The fetched FlexUserInstance + """ + payload, _, _ = self._fetch() + return FlexUserInstance( + self._version, + payload, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlexUserInstance and return response metadata + + + :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" + + 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, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + 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, + email: Union[str, object] = values.unset, + user_sid: Union[str, object] = values.unset, + locale: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Email": email, + "UserSid": user_sid, + "Locale": locale, + } + ) + 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, + 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, + instance_sid=self._solution["instance_sid"], + flex_user_sid=self._solution["flex_user_sid"], + ) + + 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 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 = 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( + { + "Email": email, + "UserSid": user_sid, + "Locale": locale, + } + ) + 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, + 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, + instance_sid=self._solution["instance_sid"], + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class FlexUserList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the FlexUserList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, instance_sid: str, flex_user_sid: str) -> FlexUserContext: + """ + Constructs a FlexUserContext + + :param instance_sid: The unique ID created by Twilio to identify a Flex instance. + :param flex_user_sid: The unique id for the flex user. + """ + return FlexUserContext( + self._version, instance_sid=instance_sid, flex_user_sid=flex_user_sid + ) + + def __call__(self, instance_sid: str, flex_user_sid: str) -> FlexUserContext: + """ + Constructs a FlexUserContext + + :param instance_sid: The unique ID created by Twilio to identify a Flex instance. + :param flex_user_sid: The unique id for the flex user. + """ + return FlexUserContext( + self._version, instance_sid=instance_sid, flex_user_sid=flex_user_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/flex_api/v2/web_channels.py b/twilio/rest/flex_api/v2/web_channels.py index b8953bd651..f25f907348 100644 --- a/twilio/rest/flex_api/v2/web_channels.py +++ b/twilio/rest/flex_api/v2/web_channels.py @@ -12,9 +12,9 @@ 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 @@ -22,7 +22,6 @@ class WebChannelsInstance(InstanceResource): - """ :ivar conversation_sid: The unique string representing the [Conversation resource](https://www.twilio.com/docs/conversations/api/conversation-resource) created. :ivar identity: The unique string representing the User created and should be authorized to participate in the Conversation. For more details, see [User Identity & Access Tokens](https://www.twilio.com/docs/conversations/identity). @@ -45,6 +44,7 @@ def __repr__(self) -> str: class WebChannelsList(ListResource): + def __init__(self, version: Version): """ Initialize the WebChannelsList @@ -56,73 +56,211 @@ def __init__(self, version: Version): self._uri = "/WebChats" + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AddressSid": address_sid, + "ChatFriendlyName": chat_friendly_name, + "CustomerFriendlyName": customer_friendly_name, + "PreEngagementData": pre_engagement_data, + "Identity": identity, + } + ) + headers = values.of( + { + "Ui-Version": ui_version, + "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, 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: """ 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( { "AddressSid": address_sid, "ChatFriendlyName": chat_friendly_name, "CustomerFriendlyName": customer_friendly_name, "PreEngagementData": pre_engagement_data, + "Identity": identity, } ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers = values.of( + { + "Ui-Version": ui_version, + "Content-Type": "application/x-www-form-urlencoded", + } ) - return WebChannelsInstance(self._version, payload) + 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, 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 """ - data = values.of( - { - "AddressSid": address_sid, - "ChatFriendlyName": chat_friendly_name, - "CustomerFriendlyName": customer_friendly_name, - "PreEngagementData": pre_engagement_data, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return WebChannelsInstance(self._version, payload) + :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: """ diff --git a/twilio/rest/frontline_api/FrontlineApiBase.py b/twilio/rest/frontline_api/FrontlineApiBase.py index 302854dc0c..d9dadc16e9 100644 --- a/twilio/rest/frontline_api/FrontlineApiBase.py +++ b/twilio/rest/frontline_api/FrontlineApiBase.py @@ -17,6 +17,7 @@ class FrontlineApiBase(Domain): + def __init__(self, twilio: Client): """ Initialize the FrontlineApi Domain diff --git a/twilio/rest/frontline_api/v1/__init__.py b/twilio/rest/frontline_api/v1/__init__.py index d2629dd5a0..610ed37194 100644 --- a/twilio/rest/frontline_api/v1/__init__.py +++ b/twilio/rest/frontline_api/v1/__init__.py @@ -19,6 +19,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of FrontlineApi diff --git a/twilio/rest/frontline_api/v1/user.py b/twilio/rest/frontline_api/v1/user.py index aa279937e8..f3cb7f3b25 100644 --- a/twilio/rest/frontline_api/v1/user.py +++ b/twilio/rest/frontline_api/v1/user.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, Optional, Union -from twilio.base import values +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 @@ -22,6 +22,7 @@ class UserInstance(InstanceResource): + class StateType(object): ACTIVE = "active" DEACTIVATED = "deactivated" @@ -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 @@ -146,6 +214,7 @@ def __repr__(self) -> str: class UserContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the UserContext @@ -161,6 +230,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Users/{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) -> UserInstance: """ Fetch the UserInstance @@ -168,17 +253,43 @@ def fetch(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return UserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserInstance: """ @@ -187,17 +298,59 @@ async def fetch_async(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return UserInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Avatar": avatar, + "State": state, + "IsAvailable": serialize.boolean_to_string(is_available), + } + ) + 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, @@ -216,22 +369,71 @@ def update( :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( { "FriendlyName": friendly_name, "Avatar": avatar, "State": state, - "IsAvailable": is_available, + "IsAvailable": serialize.boolean_to_string(is_available), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return UserInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -250,22 +452,39 @@ async def update_async( :returns: The updated UserInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Avatar": avatar, - "State": state, - "IsAvailable": is_available, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return UserInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -278,6 +497,7 @@ def __repr__(self) -> str: class UserList(ListResource): + def __init__(self, version: Version): """ Initialize the UserList diff --git a/twilio/rest/iam/IamBase.py b/twilio/rest/iam/IamBase.py new file mode 100644 index 0000000000..fc056efe43 --- /dev/null +++ b/twilio/rest/iam/IamBase.py @@ -0,0 +1,31 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + NOTE: This class is auto generated by OpenAPI Generator. + https://openapi-generator.tech + Do not edit the class manually. +""" + +from twilio.base.domain import Domain +from twilio.rest import Client + + +class IamBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Iam Domain + + :returns: Domain for Iam + """ + super().__init__(twilio, "https://iam.twilio.com") + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/iam/__init__.py b/twilio/rest/iam/__init__.py new file mode 100644 index 0000000000..994ecee62f --- /dev/null +++ b/twilio/rest/iam/__init__.py @@ -0,0 +1,25 @@ +from warnings import warn + +from twilio.rest.iam.IamBase import IamBase +from twilio.rest.iam.v1.api_key import ApiKeyList +from twilio.rest.iam.v1.get_api_keys import GetApiKeysList + + +class Iam(IamBase): + @property + def api_key(self) -> ApiKeyList: + warn( + "api_key is deprecated. Use v1.api_key instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.api_key + + @property + def get_api_keys(self) -> GetApiKeysList: + warn( + "get_api_keys is deprecated. Use v1.get_api_keys instead.", + DeprecationWarning, + stacklevel=2, + ) + return self.v1.get_api_keys diff --git a/twilio/rest/iam/v1/__init__.py b/twilio/rest/iam/v1/__init__.py new file mode 100644 index 0000000000..cef8af5122 --- /dev/null +++ b/twilio/rest/iam/v1/__init__.py @@ -0,0 +1,90 @@ +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 Optional +from twilio.base.version import Version +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.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): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Iam + + :param domain: The Twilio.iam domain + """ + super().__init__(domain, "v1") + self._api_key: Optional[ApiKeyList] = None + self._get_api_keys: Optional[GetApiKeysList] = 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: + if self._api_key is None: + self._api_key = ApiKeyList(self) + return self._api_key + + @property + def get_api_keys(self) -> GetApiKeysList: + if self._get_api_keys is None: + self._get_api_keys = GetApiKeysList(self) + return self._get_api_keys + + @property + 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: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/iam/v1/api_key.py b/twilio/rest/iam/v1/api_key.py new file mode 100644 index 0000000000..c99f3ff2a5 --- /dev/null +++ b/twilio/rest/iam/v1/api_key.py @@ -0,0 +1,570 @@ +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_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ApiKeyInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Key resource. + :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 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). + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + 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.policy: Optional[Dict[str, object]] = payload.get("policy") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ApiKeyContext] = None + + @property + def _proxy(self) -> "ApiKeyContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ApiKeyContext for this ApiKeyInstance + """ + if self._context is None: + self._context = ApiKeyContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ApiKeyInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched ApiKeyInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ApiKeyInstance": + """ + Asynchronous coroutine to fetch the ApiKeyInstance + + + :returns: The fetched 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, + policy: Union[object, object] = values.unset, + ) -> "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 + """ + return self._proxy.update( + friendly_name=friendly_name, + policy=policy, + ) + + 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 + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApiKeyContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ApiKeyContext + + :param version: Version that contains the resource + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + 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 + + + :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 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 ApiKeyInstance + + + :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 ApiKeyInstance 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) -> ApiKeyInstance: + """ + Fetch the ApiKeyInstance + + + :returns: The fetched ApiKeyInstance + """ + payload, _, _ = self._fetch() + return ApiKeyInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ApiKeyInstance and return response metadata + + + :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" + + 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"], + ) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Policy": serialize.object(policy), + } + ) + 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, + policy: Union[object, object] = values.unset, + ) -> 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( + { + "FriendlyName": friendly_name, + "Policy": serialize.object(policy), + } + ) + 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, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ApiKeyList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ApiKeyList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> ApiKeyContext: + """ + Constructs a ApiKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return ApiKeyContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ApiKeyContext: + """ + Constructs a ApiKeyContext + + :param sid: The Twilio-provided string that uniquely identifies the Key resource to update. + """ + return ApiKeyContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/iam/v1/get_api_keys.py b/twilio/rest/iam/v1/get_api_keys.py new file mode 100644 index 0000000000..14bd127d89 --- /dev/null +++ b/twilio/rest/iam/v1/get_api_keys.py @@ -0,0 +1,498 @@ +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, 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 GetApiKeysInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the Key resource. + :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]): + 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.flags: Optional[List[str]] = payload.get("flags") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class GetApiKeysPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> GetApiKeysInstance: + """ + Build an instance of GetApiKeysInstance + + :param payload: Payload response from the API + """ + + return GetApiKeysInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class GetApiKeysList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the GetApiKeysList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Keys" + + def stream( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[GetApiKeysInstance]: + """ + Streams GetApiKeysInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(account_sid=account_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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[GetApiKeysInstance]: + """ + Asynchronously streams GetApiKeysInstance 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 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: 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, 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, + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[GetApiKeysInstance]: + """ + Lists GetApiKeysInstance 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 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: list that will contain up to limit results + """ + + return list( + self.stream( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + account_sid: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[GetApiKeysInstance]: + """ + Asynchronously lists GetApiKeysInstance 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 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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + account_sid=account_sid, + limit=limit, + page_size=page_size, + ) + ] + + 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, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> GetApiKeysPage: + """ + Retrieve a single page of GetApiKeysInstance records from the API. + Request is executed immediately + + :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: Page of GetApiKeysInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return GetApiKeysPage(self._version, response) + + async def page_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, + ) -> GetApiKeysPage: + """ + Asynchronously retrieve a single page of GetApiKeysInstance records from the API. + Request is executed immediately + + :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: Page of GetApiKeysInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of GetApiKeysInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return GetApiKeysPage(self._version, response) + + async def get_page_async(self, target_url: str) -> GetApiKeysPage: + """ + Asynchronously retrieve a specific page of GetApiKeysInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of GetApiKeysInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return GetApiKeysPage(self._version, response) + + 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..a89d5cc60b --- /dev/null +++ b/twilio/rest/iam/v1/new_api_key.py @@ -0,0 +1,248 @@ +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): + + 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 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["NewApiKeyInstance.Keytype", 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["NewApiKeyInstance.Keytype", 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: + :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["NewApiKeyInstance.Keytype", 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: + :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["NewApiKeyInstance.Keytype", 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["NewApiKeyInstance.Keytype", 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: + :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["NewApiKeyInstance.Keytype", 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: + :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..1a8e3ecd22 --- /dev/null +++ b/twilio/rest/iam/v1/o_auth_app.py @@ -0,0 +1,835 @@ +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 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.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, + "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 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.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 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.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, + "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 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.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, + "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 efe713ba03..e2d5c3328d 100644 --- a/twilio/rest/insights/InsightsBase.py +++ b/twilio/rest/insights/InsightsBase.py @@ -14,9 +14,12 @@ 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): + def __init__(self, twilio: Client): """ Initialize the Insights Domain @@ -25,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: @@ -35,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/__init__.py b/twilio/rest/insights/v1/__init__.py index b5b6c44863..8f7d1946f0 100644 --- a/twilio/rest/insights/v1/__init__.py +++ b/twilio/rest/insights/v1/__init__.py @@ -23,6 +23,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Insights diff --git a/twilio/rest/insights/v1/call/__init__.py b/twilio/rest/insights/v1/call/__init__.py index 32672015ba..89516703cd 100644 --- a/twilio/rest/insights/v1/call/__init__.py +++ b/twilio/rest/insights/v1/call/__init__.py @@ -12,8 +12,9 @@ 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 @@ -26,7 +27,6 @@ class CallInstance(InstanceResource): - """ :ivar sid: :ivar url: @@ -45,6 +45,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CallContext] = None @property @@ -80,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: """ @@ -119,6 +138,7 @@ def __repr__(self) -> str: class CallContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CallContext @@ -139,6 +159,22 @@ def __init__(self, version: Version, sid: str): self._events: Optional[EventList] = None self._metrics: Optional[MetricList] = None + 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) -> CallInstance: """ Fetch the CallInstance @@ -146,17 +182,43 @@ def fetch(self) -> CallInstance: :returns: The fetched CallInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CallInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CallInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CallInstance: """ @@ -165,17 +227,27 @@ async def fetch_async(self) -> CallInstance: :returns: The fetched CallInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CallInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CallInstance( + 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: @@ -236,6 +308,7 @@ def __repr__(self) -> str: class CallList(ListResource): + def __init__(self, version: Version): """ Initialize the CallList diff --git a/twilio/rest/insights/v1/call/annotation.py b/twilio/rest/insights/v1/call/annotation.py index e9ca222180..5bda909b68 100644 --- a/twilio/rest/insights/v1/call/annotation.py +++ b/twilio/rest/insights/v1/call/annotation.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, List, Optional, Union -from twilio.base import deserialize, values +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 +22,7 @@ class AnnotationInstance(InstanceResource): + class AnsweredBy(object): UNKNOWN_ANSWERED_BY = "unknown_answered_by" HUMAN = "human" @@ -40,12 +41,12 @@ class ConnectivityIssue(object): :ivar account_sid: The unique SID identifier of the Account. :ivar answered_by: :ivar connectivity_issue: - :ivar 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 - :ivar spam: Specify 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. Is of type Boolean: true, false. Use true if the call was a spam call. - :ivar 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]. - :ivar comment: Specify any comments pertaining to the call. This of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. - :ivar incident: Associate this call with an incident or support ticket. This is of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. - :ivar url: The URL of this resource. + :ivar quality_issues: Specifies if the call had any subjective quality issues. Possible values are one or more of `no_quality_issue`, `low_volume`, `choppy_robotic`, `echo`, `dtmf`, `latency`, `owa`, or `static_noise`. + :ivar spam: Specifies 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. Is of type Boolean: true, false. Use true if the call was a spam call. + :ivar call_score: Specifies the Call Score, if available. 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]. + :ivar comment: Specifies any comments pertaining to the call. Twilio does not treat this field as PII, so no PII should be included in comments. + :ivar incident: Incident or support ticket associated with this call. The `incident` property 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`. + :ivar url: """ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): @@ -56,9 +57,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): self.answered_by: Optional["AnnotationInstance.AnsweredBy"] = payload.get( "answered_by" ) - self.connectivity_issue: Optional[ - "AnnotationInstance.ConnectivityIssue" - ] = payload.get("connectivity_issue") + self.connectivity_issue: Optional["AnnotationInstance.ConnectivityIssue"] = ( + payload.get("connectivity_issue") + ) self.quality_issues: Optional[List[str]] = payload.get("quality_issues") self.spam: Optional[bool] = payload.get("spam") self.call_score: Optional[int] = deserialize.integer(payload.get("call_score")) @@ -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, @@ -121,11 +141,11 @@ def update( :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: Specify 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. Is of type Boolean: true, false. Use true if the call was a spam call. + :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. This of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. - :param incident: Associate this call with an incident or support ticket. This is of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. + :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 """ @@ -156,11 +176,11 @@ async def update_async( :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: Specify 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. Is of type Boolean: true, false. Use true if the call was a spam call. + :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. This of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. - :param incident: Associate this call with an incident or support ticket. This is of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. + :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 """ @@ -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 @@ -185,6 +275,7 @@ def __repr__(self) -> str: class AnnotationContext(InstanceContext): + def __init__(self, version: Version, call_sid: str): """ Initialize the AnnotationContext @@ -200,6 +291,22 @@ def __init__(self, version: Version, call_sid: str): } self._uri = "/Voice/{call_sid}/Annotation".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) -> AnnotationInstance: """ Fetch the AnnotationInstance @@ -207,17 +314,43 @@ def fetch(self) -> AnnotationInstance: :returns: The fetched AnnotationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], ) - return AnnotationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AnnotationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AnnotationInstance: """ @@ -226,19 +359,29 @@ async def fetch_async(self) -> AnnotationInstance: :returns: The fetched AnnotationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AnnotationInstance( + self._version, + payload, + call_sid=self._solution["call_sid"], ) - return AnnotationInstance( + 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( + def _update( self, answered_by: Union["AnnotationInstance.AnsweredBy", object] = values.unset, connectivity_issue: Union[ @@ -249,43 +392,74 @@ 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 - - :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: Specify 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. Is of type Boolean: true, false. 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. This of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. - :param incident: Associate this call with an incident or support ticket. This is of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. + Internal helper for update operation - :returns: The updated AnnotationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "AnsweredBy": answered_by, "ConnectivityIssue": connectivity_issue, "QualityIssues": quality_issues, - "Spam": spam, + "Spam": serialize.boolean_to_string(spam), "CallScore": call_score, "Comment": comment, "Incident": incident, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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[ @@ -296,42 +470,151 @@ 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: - :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: Specify 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. Is of type Boolean: true, false. Use true if the call was a spam call. + :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. This of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. - :param incident: Associate this call with an incident or support ticket. This is of type string with a max limit of 100 characters. Twilio does not treat this field as PII, so don’t put any PII in here. + :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( { "AnsweredBy": answered_by, "ConnectivityIssue": connectivity_issue, "QualityIssues": quality_issues, - "Spam": spam, + "Spam": serialize.boolean_to_string(spam), "CallScore": call_score, "Comment": comment, "Incident": incident, } ) + 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, + 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 @@ -343,6 +626,7 @@ def __repr__(self) -> str: class AnnotationList(ListResource): + def __init__(self, version: Version, call_sid: str): """ Initialize the AnnotationList diff --git a/twilio/rest/insights/v1/call/call_summary.py b/twilio/rest/insights/v1/call/call_summary.py index dc871eb8b7..edb1ba1178 100644 --- a/twilio/rest/insights/v1/call/call_summary.py +++ b/twilio/rest/insights/v1/call/call_summary.py @@ -12,10 +12,10 @@ 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 @@ -23,6 +23,7 @@ class CallSummaryInstance(InstanceResource): + class AnsweredBy(object): UNKNOWN = "unknown" MACHINE_START = "machine_start" @@ -47,35 +48,36 @@ class CallType(object): SIP = "sip" TRUNKING = "trunking" CLIENT = "client" + WHATSAPP = "whatsapp" class ProcessingState(object): COMPLETE = "complete" PARTIAL = "partial" """ - :ivar account_sid: - :ivar call_sid: + :ivar account_sid: The unique SID identifier of the Account. + :ivar call_sid: The unique SID identifier of the Call. :ivar call_type: :ivar call_state: :ivar answered_by: :ivar processing_state: - :ivar created_time: - :ivar start_time: - :ivar end_time: - :ivar duration: - :ivar connect_duration: - :ivar _from: - :ivar to: - :ivar carrier_edge: - :ivar client_edge: - :ivar sdk_edge: - :ivar sip_edge: - :ivar tags: - :ivar url: - :ivar attributes: - :ivar properties: - :ivar trust: - :ivar annotation: + :ivar created_time: The time at which the Call was created, given in ISO 8601 format. Can be different from `start_time` in the event of queueing due to CPS + :ivar start_time: The time at which the Call was started, given in ISO 8601 format. + :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: `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: `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. """ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): @@ -92,9 +94,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): self.answered_by: Optional["CallSummaryInstance.AnsweredBy"] = payload.get( "answered_by" ) - self.processing_state: Optional[ - "CallSummaryInstance.ProcessingState" - ] = payload.get("processing_state") + self.processing_state: Optional["CallSummaryInstance.ProcessingState"] = ( + payload.get("processing_state") + ) self.created_time: Optional[datetime] = deserialize.iso8601_datetime( payload.get("created_time") ) @@ -124,6 +126,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): self._solution = { "call_sid": call_sid, } + self._context: Optional[CallSummaryContext] = None @property @@ -150,7 +153,7 @@ def fetch( """ Fetch the CallSummaryInstance - :param processing_state: + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. :returns: The fetched CallSummaryInstance """ @@ -167,7 +170,7 @@ async def fetch_async( """ Asynchronous coroutine to fetch the CallSummaryInstance - :param processing_state: + :param processing_state: The Processing State of this Call Summary. One of `complete`, `partial` or `all`. :returns: The fetched CallSummaryInstance """ @@ -175,6 +178,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 @@ -186,12 +223,13 @@ def __repr__(self) -> str: class CallSummaryContext(InstanceContext): + def __init__(self, version: Version, call_sid: str): """ Initialize the CallSummaryContext :param version: Version that contains the resource - :param call_sid: + :param call_sid: The unique SID identifier of the Call. """ super().__init__(version) @@ -201,64 +239,144 @@ 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: + Internal helper for fetch operation - :returns: The fetched CallSummaryInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "ProcessingState": processing_state, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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: + :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, } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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 @@ -270,12 +388,13 @@ def __repr__(self) -> str: class CallSummaryList(ListResource): + def __init__(self, version: Version, call_sid: str): """ Initialize the CallSummaryList :param version: Version that contains the resource - :param call_sid: + :param call_sid: The unique SID identifier of the Call. """ super().__init__(version) diff --git a/twilio/rest/insights/v1/call/event.py b/twilio/rest/insights/v1/call/event.py index 22f6c52515..ca9b99ccc6 100644 --- a/twilio/rest/insights/v1/call/event.py +++ b/twilio/rest/insights/v1/call/event.py @@ -12,9 +12,9 @@ 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 @@ -23,6 +23,7 @@ class EventInstance(InstanceResource): + class Level(object): UNKNOWN = "UNKNOWN" DEBUG = "DEBUG" @@ -38,17 +39,17 @@ class TwilioEdge(object): CLIENT_EDGE = "client_edge" """ - :ivar timestamp: - :ivar call_sid: - :ivar account_sid: + :ivar timestamp: Event time. + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. :ivar edge: - :ivar group: + :ivar group: Event group. :ivar level: - :ivar name: - :ivar carrier_edge: - :ivar sip_edge: - :ivar sdk_edge: - :ivar client_edge: + :ivar name: Event name. + :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. """ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): @@ -81,12 +82,14 @@ def __repr__(self) -> str: class EventPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: """ Build an instance of EventInstance :param payload: Payload response from the API """ + return EventInstance( self._version, payload, call_sid=self._solution["call_sid"] ) @@ -101,12 +104,13 @@ def __repr__(self) -> str: class EventList(ListResource): + def __init__(self, version: Version, call_sid: str): """ Initialize the EventList :param version: Version that contains the resource - :param call_sid: + :param call_sid: The unique SID identifier of the Call. """ super().__init__(version) @@ -129,7 +133,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "EventInstance.TwilioEdge" edge: + :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 @@ -156,7 +160,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "EventInstance.TwilioEdge" edge: + :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 @@ -171,6 +175,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, @@ -182,7 +242,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "EventInstance.TwilioEdge" edge: + :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 @@ -192,6 +252,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( edge=edge, @@ -211,7 +272,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "EventInstance.TwilioEdge" edge: + :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 @@ -221,6 +282,7 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( @@ -230,6 +292,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, @@ -241,7 +359,7 @@ def page( Retrieve a single page of EventInstance records from the API. Request is executed immediately - :param edge: + :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 @@ -257,8 +375,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return EventPage(self._version, response, self._solution) + 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 EventPage(self._version, response, solution=self._solution) async def page_async( self, @@ -271,7 +395,7 @@ async def page_async( Asynchronously retrieve a single page of EventInstance records from the API. Request is executed immediately - :param edge: + :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 @@ -287,10 +411,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return EventPage(self._version, response, self._solution) + 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: """ @@ -302,7 +506,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: """ @@ -314,7 +518,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 06bb972620..7cf72240b7 100644 --- a/twilio/rest/insights/v1/call/metric.py +++ b/twilio/rest/insights/v1/call/metric.py @@ -12,9 +12,9 @@ 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 @@ -23,6 +23,7 @@ class MetricInstance(InstanceResource): + class StreamDirection(object): UNKNOWN = "unknown" INBOUND = "inbound" @@ -37,15 +38,15 @@ class TwilioEdge(object): CLIENT_EDGE = "client_edge" """ - :ivar timestamp: - :ivar call_sid: - :ivar account_sid: + :ivar timestamp: Timestamp of metric sample. Samples are taken every 10 seconds and contain the metrics for the previous 10 seconds. + :ivar call_sid: The unique SID identifier of the Call. + :ivar account_sid: The unique SID identifier of the Account. :ivar edge: :ivar direction: - :ivar carrier_edge: - :ivar sip_edge: - :ivar sdk_edge: - :ivar client_edge: + :ivar carrier_edge: Contains metrics and properties for the Twilio media gateway of a PSTN call. + :ivar sip_edge: Contains metrics and properties for the Twilio media gateway of a SIP Interface or Trunking call. + :ivar sdk_edge: Contains metrics and properties for the SDK sensor library for Client calls. + :ivar client_edge: Contains metrics and properties for the Twilio media gateway of a Client call. """ def __init__(self, version: Version, payload: Dict[str, Any], call_sid: str): @@ -78,12 +79,14 @@ def __repr__(self) -> str: class MetricPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MetricInstance: """ Build an instance of MetricInstance :param payload: Payload response from the API """ + return MetricInstance( self._version, payload, call_sid=self._solution["call_sid"] ) @@ -98,12 +101,13 @@ def __repr__(self) -> str: class MetricList(ListResource): + def __init__(self, version: Version, call_sid: str): """ Initialize the MetricList :param version: Version that contains the resource - :param call_sid: + :param call_sid: The unique SID identifier of the Call. """ super().__init__(version) @@ -127,8 +131,8 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "MetricInstance.TwilioEdge" edge: - :param "MetricInstance.StreamDirection" direction: + :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 @@ -156,8 +160,8 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "MetricInstance.TwilioEdge" edge: - :param "MetricInstance.StreamDirection" direction: + :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 @@ -174,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, @@ -186,8 +250,8 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "MetricInstance.TwilioEdge" edge: - :param "MetricInstance.StreamDirection" direction: + :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 @@ -197,6 +261,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( edge=edge, @@ -218,8 +283,8 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "MetricInstance.TwilioEdge" edge: - :param "MetricInstance.StreamDirection" direction: + :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 @@ -229,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( @@ -239,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, @@ -251,8 +379,8 @@ def page( Retrieve a single page of MetricInstance records from the API. Request is executed immediately - :param edge: - :param direction: + :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 @@ -269,8 +397,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MetricPage(self._version, response, self._solution) + 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 MetricPage(self._version, response, solution=self._solution) async def page_async( self, @@ -284,8 +418,8 @@ async def page_async( Asynchronously retrieve a single page of MetricInstance records from the API. Request is executed immediately - :param edge: - :param direction: + :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 @@ -302,10 +436,96 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MetricPage(self._version, response, self._solution) + 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: """ @@ -317,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: """ @@ -329,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 4e428c0a0d..c1de69c6d5 100644 --- a/twilio/rest/insights/v1/call_summaries.py +++ b/twilio/rest/insights/v1/call_summaries.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class CallSummariesInstance(InstanceResource): + class AnsweredBy(object): UNKNOWN = "unknown" MACHINE_START = "machine_start" @@ -48,6 +49,7 @@ class CallType(object): SIP = "sip" TRUNKING = "trunking" CLIENT = "client" + WHATSAPP = "whatsapp" class ProcessingState(object): COMPLETE = "complete" @@ -64,28 +66,29 @@ class SortBy(object): END_TIME = "end_time" """ - :ivar account_sid: - :ivar call_sid: + :ivar account_sid: The unique SID identifier of the Account. + :ivar call_sid: The unique SID identifier of the Call. :ivar answered_by: :ivar call_type: :ivar call_state: :ivar processing_state: - :ivar created_time: - :ivar start_time: - :ivar end_time: - :ivar duration: - :ivar connect_duration: - :ivar _from: - :ivar to: - :ivar carrier_edge: - :ivar client_edge: - :ivar sdk_edge: - :ivar sip_edge: - :ivar tags: - :ivar url: - :ivar attributes: - :ivar properties: - :ivar trust: + :ivar created_time: The time at which the Call was created, given in ISO 8601 format. Can be different from `start_time` in the event of queueing due to CPS + :ivar start_time: The time at which the Call was started, given in ISO 8601 format. + :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: `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: `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. """ def __init__(self, version: Version, payload: Dict[str, Any]): @@ -102,9 +105,9 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.call_state: Optional["CallSummariesInstance.CallState"] = payload.get( "call_state" ) - self.processing_state: Optional[ - "CallSummariesInstance.ProcessingState" - ] = payload.get("processing_state") + self.processing_state: Optional["CallSummariesInstance.ProcessingState"] = ( + payload.get("processing_state") + ) self.created_time: Optional[datetime] = deserialize.iso8601_datetime( payload.get("created_time") ) @@ -129,6 +132,7 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.attributes: Optional[Dict[str, object]] = payload.get("attributes") 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") def __repr__(self) -> str: """ @@ -141,12 +145,14 @@ def __repr__(self) -> str: class CallSummariesPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CallSummariesInstance: """ Build an instance of CallSummariesInstance :param payload: Payload response from the API """ + return CallSummariesInstance(self._version, payload) def __repr__(self) -> str: @@ -159,6 +165,7 @@ def __repr__(self) -> str: class CallSummariesList(ListResource): + def __init__(self, version: Version): """ Initialize the CallSummariesList @@ -178,7 +185,6 @@ def stream( to_carrier: Union[str, object] = values.unset, from_country_code: Union[str, object] = values.unset, to_country_code: Union[str, object] = values.unset, - branded: Union[bool, object] = values.unset, verified_caller: Union[bool, object] = values.unset, has_tag: Union[bool, object] = values.unset, start_time: Union[str, object] = values.unset, @@ -193,6 +199,24 @@ def stream( 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, ) -> Iterator[CallSummariesInstance]: @@ -202,25 +226,42 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str from_: - :param str to: - :param str from_carrier: - :param str to_carrier: - :param str from_country_code: - :param str to_country_code: - :param bool branded: - :param bool verified_caller: - :param bool has_tag: - :param str start_time: - :param str end_time: - :param str call_type: - :param str call_state: - :param str direction: - :param "CallSummariesInstance.ProcessingStateRequest" processing_state: - :param "CallSummariesInstance.SortBy" sort_by: - :param str subaccount: - :param bool abnormal_session: - :param "CallSummariesInstance.AnsweredBy" answered_by: + :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 @@ -238,7 +279,6 @@ def stream( to_carrier=to_carrier, from_country_code=from_country_code, to_country_code=to_country_code, - branded=branded, verified_caller=verified_caller, has_tag=has_tag, start_time=start_time, @@ -251,6 +291,24 @@ def stream( 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"], ) @@ -264,7 +322,6 @@ async def stream_async( to_carrier: Union[str, object] = values.unset, from_country_code: Union[str, object] = values.unset, to_country_code: Union[str, object] = values.unset, - branded: Union[bool, object] = values.unset, verified_caller: Union[bool, object] = values.unset, has_tag: Union[bool, object] = values.unset, start_time: Union[str, object] = values.unset, @@ -279,6 +336,24 @@ async def stream_async( 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, ) -> AsyncIterator[CallSummariesInstance]: @@ -288,25 +363,42 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str from_: - :param str to: - :param str from_carrier: - :param str to_carrier: - :param str from_country_code: - :param str to_country_code: - :param bool branded: - :param bool verified_caller: - :param bool has_tag: - :param str start_time: - :param str end_time: - :param str call_type: - :param str call_state: - :param str direction: - :param "CallSummariesInstance.ProcessingStateRequest" processing_state: - :param "CallSummariesInstance.SortBy" sort_by: - :param str subaccount: - :param bool abnormal_session: - :param "CallSummariesInstance.AnsweredBy" answered_by: + :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 @@ -324,7 +416,6 @@ async def stream_async( to_carrier=to_carrier, from_country_code=from_country_code, to_country_code=to_country_code, - branded=branded, verified_caller=verified_caller, has_tag=has_tag, start_time=start_time, @@ -337,11 +428,301 @@ async def stream_async( 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"], ) 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, @@ -350,7 +731,6 @@ def list( to_carrier: Union[str, object] = values.unset, from_country_code: Union[str, object] = values.unset, to_country_code: Union[str, object] = values.unset, - branded: Union[bool, object] = values.unset, verified_caller: Union[bool, object] = values.unset, has_tag: Union[bool, object] = values.unset, start_time: Union[str, object] = values.unset, @@ -365,6 +745,24 @@ def list( 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, ) -> List[CallSummariesInstance]: @@ -373,25 +771,42 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str from_: - :param str to: - :param str from_carrier: - :param str to_carrier: - :param str from_country_code: - :param str to_country_code: - :param bool branded: - :param bool verified_caller: - :param bool has_tag: - :param str start_time: - :param str end_time: - :param str call_type: - :param str call_state: - :param str direction: - :param "CallSummariesInstance.ProcessingStateRequest" processing_state: - :param "CallSummariesInstance.SortBy" sort_by: - :param str subaccount: - :param bool abnormal_session: - :param "CallSummariesInstance.AnsweredBy" answered_by: + :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 @@ -401,6 +816,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( from_=from_, @@ -409,7 +825,6 @@ def list( to_carrier=to_carrier, from_country_code=from_country_code, to_country_code=to_country_code, - branded=branded, verified_caller=verified_caller, has_tag=has_tag, start_time=start_time, @@ -422,6 +837,24 @@ def list( 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, ) @@ -435,7 +868,6 @@ async def list_async( to_carrier: Union[str, object] = values.unset, from_country_code: Union[str, object] = values.unset, to_country_code: Union[str, object] = values.unset, - branded: Union[bool, object] = values.unset, verified_caller: Union[bool, object] = values.unset, has_tag: Union[bool, object] = values.unset, start_time: Union[str, object] = values.unset, @@ -450,6 +882,24 @@ async def list_async( 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, ) -> List[CallSummariesInstance]: @@ -458,25 +908,42 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str from_: - :param str to: - :param str from_carrier: - :param str to_carrier: - :param str from_country_code: - :param str to_country_code: - :param bool branded: - :param bool verified_caller: - :param bool has_tag: - :param str start_time: - :param str end_time: - :param str call_type: - :param str call_state: - :param str direction: - :param "CallSummariesInstance.ProcessingStateRequest" processing_state: - :param "CallSummariesInstance.SortBy" sort_by: - :param str subaccount: - :param bool abnormal_session: - :param "CallSummariesInstance.AnsweredBy" answered_by: + :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 @@ -486,6 +953,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,7 +963,6 @@ async def list_async( to_carrier=to_carrier, from_country_code=from_country_code, to_country_code=to_country_code, - branded=branded, verified_caller=verified_caller, has_tag=has_tag, start_time=start_time, @@ -508,11 +975,299 @@ async def list_async( 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, ) ] + def list_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, + ) -> ApiResponse: + """ + 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 = 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, @@ -521,7 +1276,6 @@ def page( to_carrier: Union[str, object] = values.unset, from_country_code: Union[str, object] = values.unset, to_country_code: Union[str, object] = values.unset, - branded: Union[bool, object] = values.unset, verified_caller: Union[bool, object] = values.unset, has_tag: Union[bool, object] = values.unset, start_time: Union[str, object] = values.unset, @@ -536,6 +1290,24 @@ def page( 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, @@ -544,25 +1316,42 @@ def page( Retrieve a single page of CallSummariesInstance records from the API. Request is executed immediately - :param from_: - :param to: - :param from_carrier: - :param to_carrier: - :param from_country_code: - :param to_country_code: - :param branded: - :param verified_caller: - :param has_tag: - :param start_time: - :param end_time: - :param call_type: - :param call_state: - :param direction: - :param processing_state: - :param sort_by: - :param subaccount: - :param abnormal_session: - :param answered_by: + :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 @@ -577,9 +1366,8 @@ def page( "ToCarrier": to_carrier, "FromCountryCode": from_country_code, "ToCountryCode": to_country_code, - "Branded": branded, - "VerifiedCaller": verified_caller, - "HasTag": has_tag, + "VerifiedCaller": serialize.boolean_to_string(verified_caller), + "HasTag": serialize.boolean_to_string(has_tag), "StartTime": start_time, "EndTime": end_time, "CallType": call_type, @@ -588,15 +1376,41 @@ def page( "ProcessingState": processing_state, "SortBy": sort_by, "Subaccount": subaccount, - "AbnormalSession": abnormal_session, + "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, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CallSummariesPage(self._version, response) async def page_async( @@ -607,7 +1421,6 @@ async def page_async( to_carrier: Union[str, object] = values.unset, from_country_code: Union[str, object] = values.unset, to_country_code: Union[str, object] = values.unset, - branded: Union[bool, object] = values.unset, verified_caller: Union[bool, object] = values.unset, has_tag: Union[bool, object] = values.unset, start_time: Union[str, object] = values.unset, @@ -622,6 +1435,24 @@ async def page_async( 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, @@ -630,25 +1461,42 @@ async def page_async( Asynchronously retrieve a single page of CallSummariesInstance records from the API. Request is executed immediately - :param from_: - :param to: - :param from_carrier: - :param to_carrier: - :param from_country_code: - :param to_country_code: - :param branded: - :param verified_caller: - :param has_tag: - :param start_time: - :param end_time: - :param call_type: - :param call_state: - :param direction: - :param processing_state: - :param sort_by: - :param subaccount: - :param abnormal_session: - :param answered_by: + :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 @@ -663,9 +1511,8 @@ async def page_async( "ToCarrier": to_carrier, "FromCountryCode": from_country_code, "ToCountryCode": to_country_code, - "Branded": branded, - "VerifiedCaller": verified_caller, - "HasTag": has_tag, + "VerifiedCaller": serialize.boolean_to_string(verified_caller), + "HasTag": serialize.boolean_to_string(has_tag), "StartTime": start_time, "EndTime": end_time, "CallType": call_type, @@ -674,19 +1521,337 @@ async def page_async( "ProcessingState": processing_state, "SortBy": sort_by, "Subaccount": subaccount, - "AbnormalSession": abnormal_session, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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 ca0a316eee..72a54a8e96 100644 --- a/twilio/rest/insights/v1/conference/__init__.py +++ b/twilio/rest/insights/v1/conference/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,6 +27,7 @@ class ConferenceInstance(InstanceResource): + class ConferenceEndReason(object): LAST_PARTICIPANT_LEFT = "last_participant_left" CONFERENCE_ENDED_VIA_API = "conference_ended_via_api" @@ -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" @@ -70,6 +73,7 @@ class Tag(object): HIGH_LATENCY = "high_latency" LOW_MOS = "low_mos" DETECTED_SILENCE = "detected_silence" + NO_CONCURRENT_PARTICIPANTS = "no_concurrent_participants" """ :ivar conference_sid: The unique SID identifier of the Conference. @@ -135,31 +139,32 @@ def __init__( self.unique_participants: Optional[int] = deserialize.integer( payload.get("unique_participants") ) - self.end_reason: Optional[ - "ConferenceInstance.ConferenceEndReason" - ] = payload.get("end_reason") + self.end_reason: Optional["ConferenceInstance.ConferenceEndReason"] = ( + payload.get("end_reason") + ) self.ended_by: Optional[str] = payload.get("ended_by") self.mixer_region: Optional["ConferenceInstance.Region"] = payload.get( "mixer_region" ) - self.mixer_region_requested: Optional[ - "ConferenceInstance.Region" - ] = payload.get("mixer_region_requested") + self.mixer_region_requested: Optional["ConferenceInstance.Region"] = ( + payload.get("mixer_region_requested") + ) self.recording_enabled: Optional[bool] = payload.get("recording_enabled") self.detected_issues: Optional[Dict[str, object]] = payload.get( "detected_issues" ) self.tags: Optional[List["ConferenceInstance.Tag"]] = payload.get("tags") self.tag_info: Optional[Dict[str, object]] = payload.get("tag_info") - self.processing_state: Optional[ - "ConferenceInstance.ProcessingState" - ] = payload.get("processing_state") + self.processing_state: Optional["ConferenceInstance.ProcessingState"] = ( + payload.get("processing_state") + ) self.url: Optional[str] = payload.get("url") self.links: Optional[Dict[str, object]] = payload.get("links") self._solution = { "conference_sid": conference_sid or self.conference_sid, } + self._context: Optional[ConferenceContext] = None @property @@ -195,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: """ @@ -213,6 +236,7 @@ def __repr__(self) -> str: class ConferenceContext(InstanceContext): + def __init__(self, version: Version, conference_sid: str): """ Initialize the ConferenceContext @@ -230,6 +254,22 @@ def __init__(self, version: Version, conference_sid: str): self._conference_participants: Optional[ConferenceParticipantList] = None + 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) -> ConferenceInstance: """ Fetch the ConferenceInstance @@ -237,17 +277,43 @@ def fetch(self) -> ConferenceInstance: :returns: The fetched ConferenceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], ) - return ConferenceInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConferenceInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ConferenceInstance: """ @@ -256,17 +322,27 @@ async def fetch_async(self) -> ConferenceInstance: :returns: The fetched ConferenceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ConferenceInstance( + self._version, + payload, + conference_sid=self._solution["conference_sid"], ) - return ConferenceInstance( + 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: @@ -291,12 +367,14 @@ def __repr__(self) -> str: class ConferencePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ConferenceInstance: """ Build an instance of ConferenceInstance :param payload: Payload response from the API """ + return ConferenceInstance(self._version, payload) def __repr__(self) -> str: @@ -309,6 +387,7 @@ def __repr__(self) -> str: class ConferenceList(ListResource): + def __init__(self, version: Version): """ Initialize the ConferenceList @@ -434,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, @@ -473,6 +664,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( conference_sid=conference_sid, @@ -529,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( @@ -547,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, @@ -601,7 +904,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 ConferencePage(self._version, response) async def page_async( @@ -658,11 +967,145 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 e6c5489b41..ce953db174 100644 --- a/twilio/rest/insights/v1/conference/conference_participant.py +++ b/twilio/rest/insights/v1/conference/conference_participant.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class ConferenceParticipantInstance(InstanceResource): + class CallDirection(object): INBOUND = "inbound" OUTBOUND = "outbound" @@ -62,6 +63,7 @@ class Region(object): JP1 = "jp1" SG1 = "sg1" DE1 = "de1" + IN1 = "in1" """ :ivar participant_sid: SID for this participant. @@ -107,14 +109,14 @@ def __init__( self.conference_sid: Optional[str] = payload.get("conference_sid") self.call_sid: Optional[str] = payload.get("call_sid") self.account_sid: Optional[str] = payload.get("account_sid") - self.call_direction: Optional[ - "ConferenceParticipantInstance.CallDirection" - ] = payload.get("call_direction") + self.call_direction: Optional["ConferenceParticipantInstance.CallDirection"] = ( + payload.get("call_direction") + ) self._from: Optional[str] = payload.get("from") self.to: Optional[str] = payload.get("to") - self.call_status: Optional[ - "ConferenceParticipantInstance.CallStatus" - ] = payload.get("call_status") + self.call_status: Optional["ConferenceParticipantInstance.CallStatus"] = ( + payload.get("call_status") + ) self.country_code: Optional[str] = payload.get("country_code") self.is_moderator: Optional[bool] = payload.get("is_moderator") self.join_time: Optional[datetime] = deserialize.iso8601_datetime( @@ -139,15 +141,15 @@ def __init__( self.coached_participants: Optional[List[str]] = payload.get( "coached_participants" ) - self.participant_region: Optional[ - "ConferenceParticipantInstance.Region" - ] = payload.get("participant_region") - self.conference_region: Optional[ - "ConferenceParticipantInstance.Region" - ] = payload.get("conference_region") - self.call_type: Optional[ - "ConferenceParticipantInstance.CallType" - ] = payload.get("call_type") + self.participant_region: Optional["ConferenceParticipantInstance.Region"] = ( + payload.get("participant_region") + ) + self.conference_region: Optional["ConferenceParticipantInstance.Region"] = ( + payload.get("conference_region") + ) + self.call_type: Optional["ConferenceParticipantInstance.CallType"] = ( + payload.get("call_type") + ) self.processing_state: Optional[ "ConferenceParticipantInstance.ProcessingState" ] = payload.get("processing_state") @@ -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 @@ -225,6 +264,7 @@ def __repr__(self) -> str: class ConferenceParticipantContext(InstanceContext): + def __init__(self, version: Version, conference_sid: str, participant_sid: str): """ Initialize the ConferenceParticipantContext @@ -246,29 +286,47 @@ 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, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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, @@ -276,31 +334,69 @@ 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) + + async def _fetch_async( + self, + events: Union[str, object] = values.unset, + metrics: Union[str, object] = values.unset, + ) -> tuple: """ + Internal async helper for fetch operation - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Events": events, "Metrics": metrics, } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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, @@ -308,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 @@ -319,12 +439,14 @@ def __repr__(self) -> str: class ConferenceParticipantPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ConferenceParticipantInstance: """ Build an instance of ConferenceParticipantInstance :param payload: Payload response from the API """ + return ConferenceParticipantInstance( self._version, payload, conference_sid=self._solution["conference_sid"] ) @@ -339,6 +461,7 @@ def __repr__(self) -> str: class ConferenceParticipantList(ListResource): + def __init__(self, version: Version, conference_sid: str): """ Initialize the ConferenceParticipantList @@ -429,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, @@ -454,6 +647,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( participant_sid=participant_sid, @@ -489,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( @@ -500,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, @@ -533,8 +796,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ConferenceParticipantPage(self._version, response, self._solution) + 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 ConferenceParticipantPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -569,10 +840,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 ConferenceParticipantPage(self._version, response, 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: """ @@ -584,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: """ @@ -596,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 c17dd25648..c754e43850 100644 --- a/twilio/rest/insights/v1/room/__init__.py +++ b/twilio/rest/insights/v1/room/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,10 +25,12 @@ class RoomInstance(InstanceResource): + class Codec(object): VP8 = "VP8" H264 = "H264" VP9 = "VP9" + OPUS = "opus" class CreatedMethod(object): SDK = "sdk" @@ -53,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" @@ -170,6 +174,7 @@ def __init__( self._solution = { "room_sid": room_sid or self.room_sid, } + self._context: Optional[RoomContext] = None @property @@ -205,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: """ @@ -223,6 +246,7 @@ def __repr__(self) -> str: class RoomContext(InstanceContext): + def __init__(self, version: Version, room_sid: str): """ Initialize the RoomContext @@ -240,6 +264,22 @@ def __init__(self, version: Version, room_sid: str): self._participants: Optional[ParticipantList] = None + 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) -> RoomInstance: """ Fetch the RoomInstance @@ -247,17 +287,43 @@ def fetch(self) -> RoomInstance: :returns: The fetched RoomInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], ) - return RoomInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RoomInstance: """ @@ -266,17 +332,27 @@ async def fetch_async(self) -> RoomInstance: :returns: The fetched RoomInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return RoomInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], ) - return RoomInstance( + 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: @@ -301,12 +377,14 @@ def __repr__(self) -> str: class RoomPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: """ Build an instance of RoomInstance :param payload: Payload response from the API """ + return RoomInstance(self._version, payload) def __repr__(self) -> str: @@ -319,6 +397,7 @@ def __repr__(self) -> str: class RoomList(ListResource): + def __init__(self, version: Version): """ Initialize the RoomList @@ -414,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, @@ -443,6 +604,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( room_type=room_type, @@ -484,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( @@ -497,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, @@ -536,7 +779,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 RoomPage(self._version, response) async def page_async( @@ -578,11 +827,115 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 b1548c1334..9ae8554b95 100644 --- a/twilio/rest/insights/v1/room/participant.py +++ b/twilio/rest/insights/v1/room/participant.py @@ -12,10 +12,10 @@ 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 @@ -24,10 +24,12 @@ class ParticipantInstance(InstanceResource): + class Codec(object): VP8 = "VP8" H264 = "H264" VP9 = "VP9" + OPUS = "opus" class EdgeLocation(object): ASHBURN = "ashburn" @@ -42,7 +44,9 @@ class EdgeLocation(object): class RoomStatus(object): IN_PROGRESS = "in_progress" + CONNECTED = "connected" COMPLETED = "completed" + DISCONNECTED = "disconnected" class TwilioRealm(object): US1 = "us1" @@ -66,13 +70,13 @@ class TwilioRealm(object): :ivar room_sid: Unique identifier for the room. :ivar status: :ivar codecs: Codecs detected from the participant. Can be `VP8`, `H264`, or `VP9`. - :ivar end_reason: Reason the participant left the room. See [the list of possible values here](https://www.twilio.com/docs/video/video-log-analyzer/video-log-analyzer-api#end_reason). + :ivar end_reason: Reason the participant left the room. See [the list of possible values here](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#end_reason). :ivar error_code: Errors encountered by the participant. :ivar error_code_url: Twilio error code dictionary link. :ivar media_region: - :ivar properties: Object containing information about the participant's data from the room. See [below](https://www.twilio.com/docs/video/video-log-analyzer/video-log-analyzer-api#properties) for more information. + :ivar properties: Object containing information about the participant's data from the room. See [below](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#properties) for more information. :ivar edge_location: - :ivar publisher_info: Object containing information about the SDK name and version. See [below](https://www.twilio.com/docs/video/video-log-analyzer/video-log-analyzer-api#publisher_info) for more information. + :ivar publisher_info: Object containing information about the SDK name and version. See [below](https://www.twilio.com/docs/video/troubleshooting/video-log-analyzer-api#publisher_info) for more information. :ivar url: URL of the participant resource. """ @@ -115,6 +119,7 @@ def __init__( "room_sid": room_sid, "participant_sid": participant_sid or self.participant_sid, } + self._context: Optional[ParticipantContext] = None @property @@ -151,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 @@ -162,6 +185,7 @@ def __repr__(self) -> str: class ParticipantContext(InstanceContext): + def __init__(self, version: Version, room_sid: str, participant_sid: str): """ Initialize the ParticipantContext @@ -181,6 +205,22 @@ def __init__(self, version: Version, room_sid: str, participant_sid: str): **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 @@ -188,18 +228,45 @@ def fetch(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], ) - return ParticipantInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ParticipantInstance: """ @@ -208,18 +275,29 @@ async def fetch_async(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], ) - return ParticipantInstance( + 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: """ @@ -232,12 +310,14 @@ def __repr__(self) -> str: class ParticipantPage(Page): + 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, room_sid=self._solution["room_sid"] ) @@ -252,6 +332,7 @@ def __repr__(self) -> str: class ParticipantList(ListResource): + def __init__(self, version: Version, room_sid: str): """ Initialize the ParticipantList @@ -318,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, @@ -337,6 +468,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -363,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( @@ -371,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, @@ -395,8 +578,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ParticipantPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -422,10 +611,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ParticipantPage(self._version, response, self._solution) + 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: """ @@ -437,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: """ @@ -449,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 c58f502522..daf49229a9 100644 --- a/twilio/rest/insights/v1/setting.py +++ b/twilio/rest/insights/v1/setting.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, Optional, Union -from twilio.base import values +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 @@ -22,12 +22,11 @@ class SettingInstance(InstanceResource): - """ - :ivar account_sid: - :ivar advanced_features: - :ivar voice_trace: - :ivar url: + :ivar account_sid: The unique SID identifier of the Account. + :ivar advanced_features: A boolean flag indicating whether Advanced Features for Voice Insights are enabled. + :ivar voice_trace: A boolean flag indicating whether Voice Trace is enabled. + :ivar url: The URL of this resource. """ def __init__(self, version: Version, payload: Dict[str, Any]): @@ -60,7 +59,7 @@ def fetch( """ Fetch the SettingInstance - :param subaccount_sid: + :param subaccount_sid: The unique SID identifier of the Subaccount. :returns: The fetched SettingInstance """ @@ -74,7 +73,7 @@ async def fetch_async( """ Asynchronous coroutine to fetch the SettingInstance - :param subaccount_sid: + :param subaccount_sid: The unique SID identifier of the Subaccount. :returns: The fetched SettingInstance """ @@ -82,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, @@ -91,9 +118,9 @@ def update( """ Update the SettingInstance - :param advanced_features: - :param voice_trace: - :param subaccount_sid: + :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 """ @@ -112,9 +139,9 @@ async def update_async( """ Asynchronous coroutine to update the SettingInstance - :param advanced_features: - :param voice_trace: - :param subaccount_sid: + :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 """ @@ -124,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 @@ -135,6 +204,7 @@ def __repr__(self) -> str: class SettingContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the SettingContext @@ -145,28 +215,83 @@ def __init__(self, version: Version): self._uri = "/Voice/Settings" + def _fetch(self, subaccount_sid: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "SubaccountSid": subaccount_sid, + } + ) + + 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, subaccount_sid: Union[str, object] = values.unset ) -> SettingInstance: """ Fetch the SettingInstance - :param subaccount_sid: + :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, + ) + + def fetch_with_http_info( + self, subaccount_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Fetch the SettingInstance and return response metadata - data = values.of( + :param subaccount_sid: The unique SID identifier of the Subaccount. + + :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) + + 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, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + headers = values.of({}) - return SettingInstance( - self._version, - payload, + 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( @@ -175,24 +300,63 @@ async def fetch_async( """ Asynchronous coroutine to fetch the SettingInstance - :param subaccount_sid: + :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, + ) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ data = values.of( { + "AdvancedFeatures": serialize.boolean_to_string(advanced_features), + "VoiceTrace": serialize.boolean_to_string(voice_trace), "SubaccountSid": subaccount_sid, } ) + headers = values.of({}) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SettingInstance( - self._version, - payload, + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers ) def update( @@ -204,27 +368,71 @@ def update( """ Update the SettingInstance - :param advanced_features: - :param voice_trace: - :param subaccount_sid: + :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, _, _ = 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( { - "AdvancedFeatures": advanced_features, - "VoiceTrace": voice_trace, + "AdvancedFeatures": serialize.boolean_to_string(advanced_features), + "VoiceTrace": serialize.boolean_to_string(voice_trace), "SubaccountSid": subaccount_sid, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SettingInstance(self._version, payload) + 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, @@ -235,27 +443,41 @@ async def update_async( """ Asynchronous coroutine to update the SettingInstance - :param advanced_features: - :param voice_trace: - :param subaccount_sid: + :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 """ - data = values.of( - { - "AdvancedFeatures": advanced_features, - "VoiceTrace": voice_trace, - "SubaccountSid": subaccount_sid, - } + payload, _, _ = await self._update_async( + advanced_features=advanced_features, + voice_trace=voice_trace, + subaccount_sid=subaccount_sid, ) + return SettingInstance(self._version, payload) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return SettingInstance(self._version, payload) + :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: """ @@ -268,6 +490,7 @@ def __repr__(self) -> str: class SettingList(ListResource): + def __init__(self, version: Version): """ Initialize the SettingList 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..dd519de5fc --- /dev/null +++ b/twilio/rest/insights/v3/__init__.py @@ -0,0 +1,51 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Insights + Insights Domain V3 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.insights.v3.metadata import MetadataList +from twilio.rest.insights.v3.query import QueryList + + +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 + + @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 + + 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..48fe25e158 --- /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. + + 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..e40fa1c744 --- /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. + + 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/intelligence/IntelligenceBase.py b/twilio/rest/intelligence/IntelligenceBase.py new file mode 100644 index 0000000000..937e497fe9 --- /dev/null +++ b/twilio/rest/intelligence/IntelligenceBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + 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.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): + + def __init__(self, twilio: Client): + """ + Initialize the Intelligence Domain + + :returns: Domain for Intelligence + """ + super().__init__(twilio, "https://intelligence.twilio.com") + self._v2: Optional[V2] = None + self._v3: Optional[V3] = None + + @property + def v2(self) -> V2: + """ + :returns: Versions v2 of Intelligence + """ + if self._v2 is None: + 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 + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/__init__.py b/twilio/rest/intelligence/__init__.py new file mode 100644 index 0000000000..6d565b433c --- /dev/null +++ b/twilio/rest/intelligence/__init__.py @@ -0,0 +1,13 @@ +from twilio.rest.intelligence.IntelligenceBase import IntelligenceBase +from twilio.rest.intelligence.v2.service import ServiceList +from twilio.rest.intelligence.v2.transcript import TranscriptList + + +class Intelligence(IntelligenceBase): + @property + def transcripts(self) -> TranscriptList: + return self.v2.transcripts + + @property + def services(self) -> ServiceList: + return self.v2.services diff --git a/twilio/rest/intelligence/v2/__init__.py b/twilio/rest/intelligence/v2/__init__.py new file mode 100644 index 0000000000..4999146f93 --- /dev/null +++ b/twilio/rest/intelligence/v2/__init__.py @@ -0,0 +1,99 @@ +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 Optional +from twilio.base.version import Version +from twilio.base.domain import Domain +from twilio.rest.intelligence.v2.custom_operator import CustomOperatorList +from twilio.rest.intelligence.v2.operator import OperatorList +from twilio.rest.intelligence.v2.operator_attachment import OperatorAttachmentList +from twilio.rest.intelligence.v2.operator_attachments import OperatorAttachmentsList +from twilio.rest.intelligence.v2.operator_type import OperatorTypeList +from twilio.rest.intelligence.v2.prebuilt_operator import PrebuiltOperatorList +from twilio.rest.intelligence.v2.service import ServiceList +from twilio.rest.intelligence.v2.transcript import TranscriptList + + +class V2(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V2 version of Intelligence + + :param domain: The Twilio.intelligence domain + """ + super().__init__(domain, "v2") + self._custom_operators: Optional[CustomOperatorList] = None + self._operators: Optional[OperatorList] = None + self._operator_attachment: Optional[OperatorAttachmentList] = None + self._operator_attachments: Optional[OperatorAttachmentsList] = None + self._operator_type: Optional[OperatorTypeList] = None + self._prebuilt_operators: Optional[PrebuiltOperatorList] = None + self._services: Optional[ServiceList] = None + self._transcripts: Optional[TranscriptList] = None + + @property + def custom_operators(self) -> CustomOperatorList: + if self._custom_operators is None: + self._custom_operators = CustomOperatorList(self) + return self._custom_operators + + @property + def operators(self) -> OperatorList: + if self._operators is None: + self._operators = OperatorList(self) + return self._operators + + @property + def operator_attachment(self) -> OperatorAttachmentList: + if self._operator_attachment is None: + self._operator_attachment = OperatorAttachmentList(self) + return self._operator_attachment + + @property + def operator_attachments(self) -> OperatorAttachmentsList: + if self._operator_attachments is None: + self._operator_attachments = OperatorAttachmentsList(self) + return self._operator_attachments + + @property + def operator_type(self) -> OperatorTypeList: + if self._operator_type is None: + self._operator_type = OperatorTypeList(self) + return self._operator_type + + @property + def prebuilt_operators(self) -> PrebuiltOperatorList: + if self._prebuilt_operators is None: + self._prebuilt_operators = PrebuiltOperatorList(self) + return self._prebuilt_operators + + @property + def services(self) -> ServiceList: + if self._services is None: + self._services = ServiceList(self) + return self._services + + @property + def transcripts(self) -> TranscriptList: + if self._transcripts is None: + self._transcripts = TranscriptList(self) + return self._transcripts + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/custom_operator.py b/twilio/rest/intelligence/v2/custom_operator.py new file mode 100644 index 0000000000..899e6e0c6a --- /dev/null +++ b/twilio/rest/intelligence/v2/custom_operator.py @@ -0,0 +1,1245 @@ +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 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 CustomOperatorInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + 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. + :ivar sid: A 34 character string that uniquely identifies this Custom Operator. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar author: The creator of the Custom Operator. Custom Operators can only be created by a Twilio Account. + :ivar operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :ivar version: Numeric Custom Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Custom Operator. + :ivar availability: + :ivar config: Operator configuration, following the schema defined by the Operator Type. Only available on Operators created by the Account. + :ivar date_created: The date that this Custom Operator was created, given in ISO 8601 format. + :ivar date_updated: The date that this Custom Operator was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.author: Optional[str] = payload.get("author") + self.operator_type: Optional[str] = payload.get("operator_type") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.availability: Optional["CustomOperatorInstance.Availability"] = ( + payload.get("availability") + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + 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 = { + "sid": sid or self.sid, + } + + self._context: Optional[CustomOperatorContext] = None + + @property + def _proxy(self) -> "CustomOperatorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: CustomOperatorContext for this CustomOperatorInstance + """ + if self._context is None: + self._context = CustomOperatorContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the CustomOperatorInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched CustomOperatorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "CustomOperatorInstance": + """ + Asynchronous coroutine to fetch the CustomOperatorInstance + + + :returns: The fetched 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, + config: object, + if_match: Union[str, object] = values.unset, + ) -> "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. + :param if_match: The If-Match HTTP request header + + :returns: The updated CustomOperatorInstance + """ + return self._proxy.update( + friendly_name=friendly_name, + config=config, + if_match=if_match, + ) + + 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 + """ + return await self._proxy.update_async( + friendly_name=friendly_name, + config=config, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CustomOperatorContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the CustomOperatorContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Custom Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + 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 + + + :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 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 CustomOperatorInstance + + + :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 CustomOperatorInstance 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) -> CustomOperatorInstance: + """ + Fetch the CustomOperatorInstance + + + :returns: The fetched CustomOperatorInstance + """ + payload, _, _ = self._fetch() + return CustomOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomOperatorInstance and return response metadata + + + :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" + + 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"], + ) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Config": serialize.object(config), + } + ) + 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, + friendly_name: str, + config: object, + if_match: Union[str, object] = values.unset, + ) -> 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. + :param if_match: The If-Match HTTP request header + + :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( + { + "FriendlyName": friendly_name, + "Config": serialize.object(config), + } + ) + 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, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class CustomOperatorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> CustomOperatorInstance: + """ + Build an instance of CustomOperatorInstance + + :param payload: Payload response from the API + """ + + return CustomOperatorInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class CustomOperatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the CustomOperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Operators/Custom" + + def _create(self, friendly_name: str, operator_type: str, config: object) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "OperatorType": operator_type, + "Config": serialize.object(config), + } + ) + 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, operator_type: str, config: object + ) -> 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. + :param config: Operator configuration, following the schema defined by the Operator Type. + + :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( + { + "FriendlyName": friendly_name, + "OperatorType": operator_type, + "Config": serialize.object(config), + } + ) + 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, 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[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[CustomOperatorInstance]: + """ + Streams CustomOperatorInstance 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_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, + ) -> AsyncIterator[CustomOperatorInstance]: + """ + Asynchronously streams CustomOperatorInstance 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + 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[ + "CustomOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[CustomOperatorInstance]: + """ + Lists CustomOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_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, + ) -> List[CustomOperatorInstance]: + """ + Asynchronously lists CustomOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + 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[ + "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, + ) -> CustomOperatorPage: + """ + Retrieve a single page of CustomOperatorInstance records from the API. + Request is executed immediately + + :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: Page of CustomOperatorInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return CustomOperatorPage(self._version, response) + + async def page_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, + ) -> CustomOperatorPage: + """ + Asynchronously retrieve a single page of CustomOperatorInstance records from the API. + Request is executed immediately + + :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: Page of CustomOperatorInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomOperatorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return CustomOperatorPage(self._version, response) + + async def get_page_async(self, target_url: str) -> CustomOperatorPage: + """ + Asynchronously retrieve a specific page of CustomOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of CustomOperatorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return CustomOperatorPage(self._version, response) + + def get(self, sid: str) -> CustomOperatorContext: + """ + Constructs a CustomOperatorContext + + :param sid: A 34 character string that uniquely identifies this Custom Operator. + """ + return CustomOperatorContext(self._version, sid=sid) + + def __call__(self, sid: str) -> CustomOperatorContext: + """ + Constructs a CustomOperatorContext + + :param sid: A 34 character string that uniquely identifies this Custom Operator. + """ + return CustomOperatorContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/operator.py b/twilio/rest/intelligence/v2/operator.py new file mode 100644 index 0000000000..10c2ea5d5b --- /dev/null +++ b/twilio/rest/intelligence/v2/operator.py @@ -0,0 +1,757 @@ +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 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 OperatorInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + PUBLIC = "public" + DEPRECATED = "deprecated" + GENERAL_AVAILABILITY = "general-availability" + RETIRED = "retired" + + """ + :ivar account_sid: The unique SID identifier of the Account the Operator belongs to. + :ivar sid: A 34 character string that uniquely identifies this Operator. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar author: The creator of the Operator. Either Twilio or the creating Account. + :ivar operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :ivar version: Numeric Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar availability: + :ivar config: Operator configuration, following the schema defined by the Operator Type. Only available on Custom Operators created by the Account. + :ivar date_created: The date that this Operator was created, given in ISO 8601 format. + :ivar date_updated: The date that this Operator was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.author: Optional[str] = payload.get("author") + self.operator_type: Optional[str] = payload.get("operator_type") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.availability: Optional["OperatorInstance.Availability"] = payload.get( + "availability" + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + 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 = { + "sid": sid or self.sid, + } + + 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, + sid=self._solution["sid"], + ) + return self._context + + 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 __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, sid: str): + """ + Initialize the OperatorContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Operators/{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) -> OperatorInstance: + """ + Fetch the OperatorInstance + + + :returns: The fetched OperatorInstance + """ + payload, _, _ = self._fetch() + return OperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + 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, + 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) -> 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorPage(Page): + + 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): + + def __init__(self, version: Version): + """ + Initialize the OperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Operators" + + def stream( + self, + availability: Union["OperatorInstance.Availability", object] = values.unset, + language_code: 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_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, + ) -> 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + 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, + language_code: 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 "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: list that will contain up to limit results + """ + + return list( + self.stream( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_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, + ) -> 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 "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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + 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, + 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, + ) -> OperatorPage: + """ + Retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :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: Page of OperatorInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorPage(self._version, response) + + async def page_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, + ) -> OperatorPage: + """ + Asynchronously retrieve a single page of OperatorInstance records from the API. + Request is executed immediately + + :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: Page of OperatorInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + 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, sid: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param sid: A 34 character string that uniquely identifies this Operator. + """ + return OperatorContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OperatorContext: + """ + Constructs a OperatorContext + + :param sid: A 34 character string that uniquely identifies this Operator. + """ + return OperatorContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/operator_attachment.py b/twilio/rest/intelligence/v2/operator_attachment.py new file mode 100644 index 0000000000..d05769e12e --- /dev/null +++ b/twilio/rest/intelligence/v2/operator_attachment.py @@ -0,0 +1,385 @@ +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 +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 OperatorAttachmentInstance(InstanceResource): + """ + :ivar service_sid: The unique SID identifier of the Service. + :ivar operator_sid: The unique SID identifier of the Operator. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: Optional[str] = None, + operator_sid: Optional[str] = None, + ): + super().__init__(version) + + self.service_sid: Optional[str] = payload.get("service_sid") + self.operator_sid: Optional[str] = payload.get("operator_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid or self.service_sid, + "operator_sid": operator_sid or self.operator_sid, + } + + self._context: Optional[OperatorAttachmentContext] = None + + @property + def _proxy(self) -> "OperatorAttachmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorAttachmentContext for this OperatorAttachmentInstance + """ + if self._context is None: + self._context = OperatorAttachmentContext( + self._version, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + return self._context + + def create(self) -> "OperatorAttachmentInstance": + """ + Create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + return self._proxy.create() + + async def create_async(self) -> "OperatorAttachmentInstance": + """ + Asynchronous coroutine to create the OperatorAttachmentInstance + + + :returns: The created 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 + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the OperatorAttachmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorAttachmentContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str, operator_sid: str): + """ + Initialize the OperatorAttachmentContext + + :param version: Version that contains the resource + :param service_sid: The unique SID identifier of the Service. + :param operator_sid: The unique SID identifier of the Operator. Allows both Custom and Pre-built Operators. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "service_sid": service_sid, + "operator_sid": operator_sid, + } + self._uri = "/Services/{service_sid}/Operators/{operator_sid}".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) -> OperatorAttachmentInstance: + """ + Create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + payload, _, _ = self._create() + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + + def create_with_http_info(self) -> ApiResponse: + """ + Create the OperatorAttachmentInstance and return response metadata + + + :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: + """ + Asynchronous coroutine to create the OperatorAttachmentInstance + + + :returns: The created OperatorAttachmentInstance + """ + payload, _, _ = await self._create_async() + return OperatorAttachmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + operator_sid=self._solution["operator_sid"], + ) + + 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: + """ + Deletes the OperatorAttachmentInstance + + + :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 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 OperatorAttachmentInstance + + + :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 OperatorAttachmentInstance 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 __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 OperatorAttachmentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorAttachmentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, service_sid: str, operator_sid: str) -> OperatorAttachmentContext: + """ + Constructs a OperatorAttachmentContext + + :param service_sid: The unique SID identifier of the Service. + :param operator_sid: The unique SID identifier of the Operator. Allows both Custom and Pre-built Operators. + """ + return OperatorAttachmentContext( + self._version, service_sid=service_sid, operator_sid=operator_sid + ) + + def __call__( + self, service_sid: str, operator_sid: str + ) -> OperatorAttachmentContext: + """ + Constructs a OperatorAttachmentContext + + :param service_sid: The unique SID identifier of the Service. + :param operator_sid: The unique SID identifier of the Operator. Allows both Custom and Pre-built Operators. + """ + return OperatorAttachmentContext( + self._version, service_sid=service_sid, operator_sid=operator_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/operator_attachments.py b/twilio/rest/intelligence/v2/operator_attachments.py new file mode 100644 index 0000000000..0bfbacdcf7 --- /dev/null +++ b/twilio/rest/intelligence/v2/operator_attachments.py @@ -0,0 +1,260 @@ +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 +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 OperatorAttachmentsInstance(InstanceResource): + """ + :ivar service_sid: The unique SID identifier of the Service. + :ivar operator_sids: List of Operator SIDs attached to the service. Includes both Custom and Pre-built Operators. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.service_sid: Optional[str] = payload.get("service_sid") + self.operator_sids: Optional[List[str]] = payload.get("operator_sids") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "service_sid": service_sid or self.service_sid, + } + + self._context: Optional[OperatorAttachmentsContext] = None + + @property + def _proxy(self) -> "OperatorAttachmentsContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorAttachmentsContext for this OperatorAttachmentsInstance + """ + if self._context is None: + self._context = OperatorAttachmentsContext( + self._version, + service_sid=self._solution["service_sid"], + ) + return self._context + + def fetch(self) -> "OperatorAttachmentsInstance": + """ + Fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorAttachmentsInstance": + """ + Asynchronous coroutine to fetch the OperatorAttachmentsInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorAttachmentsContext(InstanceContext): + + def __init__(self, version: Version, service_sid: str): + """ + Initialize the OperatorAttachmentsContext + + :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}/Operators".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) -> OperatorAttachmentsInstance: + """ + Fetch the OperatorAttachmentsInstance + + + :returns: The fetched OperatorAttachmentsInstance + """ + payload, _, _ = self._fetch() + return OperatorAttachmentsInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorAttachmentsInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorAttachmentsList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorAttachmentsList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, service_sid: str) -> OperatorAttachmentsContext: + """ + Constructs a OperatorAttachmentsContext + + :param service_sid: The unique SID identifier of the Service. + """ + return OperatorAttachmentsContext(self._version, service_sid=service_sid) + + def __call__(self, service_sid: str) -> OperatorAttachmentsContext: + """ + Constructs a OperatorAttachmentsContext + + :param service_sid: The unique SID identifier of the Service. + """ + return OperatorAttachmentsContext(self._version, service_sid=service_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/operator_type.py b/twilio/rest/intelligence/v2/operator_type.py new file mode 100644 index 0000000000..288595ad02 --- /dev/null +++ b/twilio/rest/intelligence/v2/operator_type.py @@ -0,0 +1,736 @@ +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 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 OperatorTypeInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + BETA = "beta" + GENERAL_AVAILABILITY = "general-availability" + RETIRED = "retired" + DEPRECATED = "deprecated" + + class OutputType(object): + TEXT_CLASSIFICATION = "text-classification" + TEXT_EXTRACTION = "text-extraction" + TEXT_EXTRACTION_NORMALIZED = "text-extraction-normalized" + TEXT_GENERATION = "text-generation" + JSON = "json" + + class Provider(object): + TWILIO = "twilio" + AMAZON = "amazon" + OPENAI = "openai" + + """ + :ivar name: A unique name that references an Operator's Operator Type. + :ivar sid: A 34 character string that uniquely identifies this Operator Type. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar docs_link: Additional documentation for the Operator Type. + :ivar output_type: + :ivar supported_languages: List of languages this Operator Type supports. + :ivar provider: + :ivar availability: + :ivar configurable: Operators can be created from configurable Operator Types. + :ivar config_schema: JSON Schema for configuring an Operator with this Operator Type. Following https://json-schema.org/ + :ivar date_created: The date that this Operator Type was created, given in ISO 8601 format. + :ivar date_updated: The date that this Operator Type was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.name: Optional[str] = payload.get("name") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.docs_link: Optional[str] = payload.get("docs_link") + self.output_type: Optional["OperatorTypeInstance.OutputType"] = payload.get( + "output_type" + ) + self.supported_languages: Optional[List[str]] = payload.get( + "supported_languages" + ) + self.provider: Optional["OperatorTypeInstance.Provider"] = payload.get( + "provider" + ) + self.availability: Optional["OperatorTypeInstance.Availability"] = payload.get( + "availability" + ) + self.configurable: Optional[bool] = payload.get("configurable") + self.config_schema: Optional[Dict[str, object]] = payload.get("config_schema") + 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 = { + "sid": sid or self.sid, + } + + self._context: Optional[OperatorTypeContext] = None + + @property + def _proxy(self) -> "OperatorTypeContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: OperatorTypeContext for this OperatorTypeInstance + """ + if self._context is None: + self._context = OperatorTypeContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "OperatorTypeInstance": + """ + Fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "OperatorTypeInstance": + """ + Asynchronous coroutine to fetch the OperatorTypeInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorTypeContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the OperatorTypeContext + + :param version: Version that contains the resource + :param sid: Either a 34 character string that uniquely identifies this Operator Type or the unique name that references an Operator Type. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/OperatorTypes/{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) -> OperatorTypeInstance: + """ + Fetch the OperatorTypeInstance + + + :returns: The fetched OperatorTypeInstance + """ + payload, _, _ = self._fetch() + return OperatorTypeInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OperatorTypeInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorTypePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> OperatorTypeInstance: + """ + Build an instance of OperatorTypeInstance + + :param payload: Payload response from the API + """ + + return OperatorTypeInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OperatorTypeList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OperatorTypeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/OperatorTypes" + + def stream( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[OperatorTypeInstance]: + """ + Streams OperatorTypeInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, 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]: + """ + Asynchronously streams OperatorTypeInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, 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]: + """ + Lists OperatorTypeInstance records from the API as a 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 + the default value of 50 records. If no page_size is defined + 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( + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[OperatorTypeInstance]: + """ + Asynchronously lists OperatorTypeInstance records from the API as a 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 + the default value of 50 records. If no page_size is defined + 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( + 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, + ) -> OperatorTypePage: + """ + 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 + + :returns: Page of OperatorTypeInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorTypePage(self._version, response) + + 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, + ) -> OperatorTypePage: + """ + 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 + + :returns: Page of OperatorTypeInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorTypeInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return OperatorTypePage(self._version, response) + + async def get_page_async(self, target_url: str) -> OperatorTypePage: + """ + Asynchronously retrieve a specific page of OperatorTypeInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of OperatorTypeInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return OperatorTypePage(self._version, response) + + def get(self, sid: str) -> OperatorTypeContext: + """ + Constructs a OperatorTypeContext + + :param sid: Either a 34 character string that uniquely identifies this Operator Type or the unique name that references an Operator Type. + """ + return OperatorTypeContext(self._version, sid=sid) + + def __call__(self, sid: str) -> OperatorTypeContext: + """ + Constructs a OperatorTypeContext + + :param sid: Either a 34 character string that uniquely identifies this Operator Type or the unique name that references an Operator Type. + """ + return OperatorTypeContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/prebuilt_operator.py b/twilio/rest/intelligence/v2/prebuilt_operator.py new file mode 100644 index 0000000000..8dc5cdac4e --- /dev/null +++ b/twilio/rest/intelligence/v2/prebuilt_operator.py @@ -0,0 +1,780 @@ +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 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 PrebuiltOperatorInstance(InstanceResource): + + class Availability(object): + INTERNAL = "internal" + 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. + :ivar sid: A 34 character string that uniquely identifies this Pre-built Operator. + :ivar friendly_name: A human-readable name of this resource, up to 64 characters. + :ivar description: A human-readable description of this resource, longer than the friendly name. + :ivar author: The creator of the Operator. Pre-built Operators can only be created by Twilio. + :ivar operator_type: Operator Type for this Operator. References an existing Operator Type resource. + :ivar version: Numeric Operator version. Incremented with each update on the resource, used to ensure integrity when updating the Operator. + :ivar availability: + :ivar config: Operator configuration, following the schema defined by the Operator Type. Only available on Custom Operators created by the Account, will be empty for Pre-Built Operators. + :ivar date_created: The date that this Pre-built Operator was created, given in ISO 8601 format. + :ivar date_updated: The date that this Pre-built Operator was updated, given in ISO 8601 format. + :ivar url: The URL of this resource. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.sid: Optional[str] = payload.get("sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.author: Optional[str] = payload.get("author") + self.operator_type: Optional[str] = payload.get("operator_type") + self.version: Optional[int] = deserialize.integer(payload.get("version")) + self.availability: Optional["PrebuiltOperatorInstance.Availability"] = ( + payload.get("availability") + ) + self.config: Optional[Dict[str, object]] = payload.get("config") + 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 = { + "sid": sid or self.sid, + } + + self._context: Optional[PrebuiltOperatorContext] = None + + @property + def _proxy(self) -> "PrebuiltOperatorContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PrebuiltOperatorContext for this PrebuiltOperatorInstance + """ + if self._context is None: + self._context = PrebuiltOperatorContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "PrebuiltOperatorInstance": + """ + Fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PrebuiltOperatorInstance": + """ + Asynchronous coroutine to fetch the PrebuiltOperatorInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PrebuiltOperatorContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the PrebuiltOperatorContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Pre-built Operator. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Operators/PreBuilt/{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) -> PrebuiltOperatorInstance: + """ + Fetch the PrebuiltOperatorInstance + + + :returns: The fetched PrebuiltOperatorInstance + """ + payload, _, _ = self._fetch() + return PrebuiltOperatorInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PrebuiltOperatorInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PrebuiltOperatorPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> PrebuiltOperatorInstance: + """ + Build an instance of PrebuiltOperatorInstance + + :param payload: Payload response from the API + """ + + return PrebuiltOperatorInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class PrebuiltOperatorList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PrebuiltOperatorList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Operators/PreBuilt" + + def stream( + self, + availability: Union[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[PrebuiltOperatorInstance]: + """ + Streams PrebuiltOperatorInstance 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_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, + ) -> AsyncIterator[PrebuiltOperatorInstance]: + """ + Asynchronously streams PrebuiltOperatorInstance 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + availability=availability, + language_code=language_code, + page_size=limits["page_size"], + ) + + 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[ + "PrebuiltOperatorInstance.Availability", object + ] = values.unset, + language_code: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[PrebuiltOperatorInstance]: + """ + Lists PrebuiltOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ) + + async def list_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, + ) -> List[PrebuiltOperatorInstance]: + """ + Asynchronously lists PrebuiltOperatorInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + availability=availability, + language_code=language_code, + limit=limit, + page_size=page_size, + ) + ] + + 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[ + "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, + ) -> PrebuiltOperatorPage: + """ + Retrieve a single page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :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: Page of PrebuiltOperatorInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return PrebuiltOperatorPage(self._version, response) + + async def page_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, + ) -> PrebuiltOperatorPage: + """ + Asynchronously retrieve a single page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :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: Page of PrebuiltOperatorInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PrebuiltOperatorInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return PrebuiltOperatorPage(self._version, response) + + async def get_page_async(self, target_url: str) -> PrebuiltOperatorPage: + """ + Asynchronously retrieve a specific page of PrebuiltOperatorInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of PrebuiltOperatorInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return PrebuiltOperatorPage(self._version, response) + + def get(self, sid: str) -> PrebuiltOperatorContext: + """ + Constructs a PrebuiltOperatorContext + + :param sid: A 34 character string that uniquely identifies this Pre-built Operator. + """ + return PrebuiltOperatorContext(self._version, sid=sid) + + def __call__(self, sid: str) -> PrebuiltOperatorContext: + """ + Constructs a PrebuiltOperatorContext + + :param sid: A 34 character string that uniquely identifies this Pre-built Operator. + """ + return PrebuiltOperatorContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/service.py b/twilio/rest/intelligence/v2/service.py new file mode 100644 index 0000000000..6a16c052fe --- /dev/null +++ b/twilio/rest/intelligence/v2/service.py @@ -0,0 +1,1494 @@ +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 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 ServiceInstance(InstanceResource): + + class HttpMethod(object): + GET = "GET" + POST = "POST" + NULL = "NULL" + + """ + :ivar account_sid: The unique SID identifier of the Account the Service belongs to. + :ivar auto_redaction: Instructs the Speech Recognition service to automatically redact PII from all transcripts made on this service. + :ivar 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. + :ivar auto_transcribe: Instructs the Speech Recognition service to automatically transcribe all recordings made on the account. + :ivar 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. + :ivar date_created: The date that this Service was created, given in ISO 8601 format. + :ivar date_updated: The date that this Service was updated, given in ISO 8601 format. + :ivar friendly_name: A human readable description of this resource, up to 64 characters. + :ivar 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. + :ivar sid: A 34 character string that uniquely identifies this Service. + :ivar 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. + :ivar url: The URL of this resource. + :ivar webhook_url: The URL Twilio will request when executing the Webhook. + :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__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.auto_redaction: Optional[bool] = payload.get("auto_redaction") + self.media_redaction: Optional[bool] = payload.get("media_redaction") + self.auto_transcribe: Optional[bool] = payload.get("auto_transcribe") + self.data_logging: Optional[bool] = payload.get("data_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.friendly_name: Optional[str] = payload.get("friendly_name") + self.language_code: Optional[str] = payload.get("language_code") + self.sid: Optional[str] = payload.get("sid") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + self.webhook_url: Optional[str] = payload.get("webhook_url") + self.webhook_http_method: Optional["ServiceInstance.HttpMethod"] = payload.get( + "webhook_http_method" + ) + self.read_only_attached_operator_sids: Optional[List[str]] = payload.get( + "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 + 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 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 + + + :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 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, + 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": + """ + 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 + """ + return self._proxy.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, + ) + + 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": + """ + 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 + """ + return await self._proxy.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, + ) + + 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: + """ + 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: A 34 character string that uniquely identifies this Service. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + 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 + + + :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, + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + "EncryptionCredentialSid": encryption_credential_sid, + } + ) + 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, + 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: + """ + 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, _, _ = 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( + { + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "MediaRedaction": serialize.boolean_to_string(media_redaction), + "WebhookUrl": webhook_url, + "WebhookHttpMethod": webhook_http_method, + "EncryptionCredentialSid": encryption_credential_sid, + } + ) + 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, + 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: + """ + 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): + + 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 "" + + +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, + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "LanguageCode": language_code, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "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"}) + + 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, + 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: + """ + 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, _, _ = 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( + { + "UniqueName": unique_name, + "AutoTranscribe": serialize.boolean_to_string(auto_transcribe), + "DataLogging": serialize.boolean_to_string(data_logging), + "FriendlyName": friendly_name, + "LanguageCode": language_code, + "AutoRedaction": serialize.boolean_to_string(auto_redaction), + "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"}) + + 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, + 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, + 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 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, + 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 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, + 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 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. + 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: A 34 character string that uniquely identifies this Service. + """ + return ServiceContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ServiceContext: + """ + Constructs a ServiceContext + + :param sid: A 34 character string that uniquely identifies this Service. + """ + return ServiceContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/transcript/__init__.py b/twilio/rest/intelligence/v2/transcript/__init__.py new file mode 100644 index 0000000000..19284fa98d --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/__init__.py @@ -0,0 +1,1364 @@ +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 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 + + +class TranscriptInstance(InstanceResource): + + 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. + :ivar service_sid: The unique SID identifier of the Service. + :ivar sid: A 34 character string that uniquely identifies this Transcript. + :ivar date_created: The date that this Transcript was created, given in ISO 8601 format. + :ivar date_updated: The date that this Transcript was updated, given in ISO 8601 format. + :ivar status: + :ivar channel: Media Channel describing Transcript Source and Participant Mapping + :ivar 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. + :ivar language_code: The default language code of the audio. + :ivar customer_key: + :ivar media_start_time: The date that this Transcript's media was started, given in ISO 8601 format. + :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: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: 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.sid: Optional[str] = payload.get("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.status: Optional["TranscriptInstance.Status"] = payload.get("status") + self.channel: Optional[Dict[str, object]] = payload.get("channel") + self.data_logging: Optional[bool] = payload.get("data_logging") + self.language_code: Optional[str] = payload.get("language_code") + self.customer_key: Optional[str] = payload.get("customer_key") + self.media_start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("media_start_time") + ) + 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 + def _proxy(self) -> "TranscriptContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: TranscriptContext for this TranscriptInstance + """ + if self._context is None: + self._context = TranscriptContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TranscriptInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched TranscriptInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "TranscriptInstance": + """ + Asynchronous coroutine to fetch the TranscriptInstance + + + :returns: The fetched 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: + """ + Access the media + """ + return self._proxy.media + + @property + def operator_results(self) -> OperatorResultList: + """ + Access the operator_results + """ + return self._proxy.operator_results + + @property + def sentences(self) -> SentenceList: + """ + Access the sentences + """ + return self._proxy.sentences + + 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 TranscriptContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the TranscriptContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + 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 + + + :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 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 TranscriptInstance + + + :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 TranscriptInstance 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) -> TranscriptInstance: + """ + Fetch the TranscriptInstance + + + :returns: The fetched TranscriptInstance + """ + payload, _, _ = self._fetch() + return TranscriptInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TranscriptInstance and return response metadata + + + :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" + + 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: + """ + Access the media + """ + if self._media is None: + self._media = MediaList( + self._version, + self._solution["sid"], + ) + return self._media + + @property + def operator_results(self) -> OperatorResultList: + """ + Access the operator_results + """ + if self._operator_results is None: + self._operator_results = OperatorResultList( + self._version, + self._solution["sid"], + ) + return self._operator_results + + @property + def sentences(self) -> SentenceList: + """ + Access the sentences + """ + if self._sentences is None: + self._sentences = SentenceList( + self._version, + self._solution["sid"], + ) + return self._sentences + + 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 TranscriptPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> TranscriptInstance: + """ + Build an instance of TranscriptInstance + + :param payload: Payload response from the API + """ + + return TranscriptInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class TranscriptList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the TranscriptList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Transcripts" + + def _create( + self, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ServiceSid": service_sid, + "Channel": serialize.object(channel), + "CustomerKey": customer_key, + "MediaStartTime": serialize.iso8601_datetime(media_start_time), + } + ) + 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, + service_sid: str, + channel: object, + customer_key: Union[str, object] = values.unset, + media_start_time: Union[datetime, object] = values.unset, + ) -> 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 + :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, _, _ = 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( + { + "ServiceSid": service_sid, + "Channel": serialize.object(channel), + "CustomerKey": customer_key, + "MediaStartTime": serialize.iso8601_datetime(media_start_time), + } + ) + 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, + 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, + 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, + ) -> Iterator[TranscriptInstance]: + """ + Streams TranscriptInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + 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"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_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, + ) -> AsyncIterator[TranscriptInstance]: + """ + Asynchronously streams TranscriptInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_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"], + ) + + 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, + 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, + ) -> List[TranscriptInstance]: + """ + Lists TranscriptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + 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, + ) + ) + + async def list_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, + ) -> List[TranscriptInstance]: + """ + Asynchronously lists TranscriptInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_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, + ) + ] + + 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, + 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, + ) -> TranscriptPage: + """ + Retrieve a single page of TranscriptInstance records from the API. + Request is executed immediately + + :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: Page of TranscriptInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return TranscriptPage(self._version, response) + + async def page_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, + ) -> TranscriptPage: + """ + Asynchronously retrieve a single page of TranscriptInstance records from the API. + Request is executed immediately + + :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: Page of TranscriptInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return TranscriptPage(self._version, response) + + async def get_page_async(self, target_url: str) -> TranscriptPage: + """ + Asynchronously retrieve a specific page of TranscriptInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of TranscriptInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return TranscriptPage(self._version, response) + + def get(self, sid: str) -> TranscriptContext: + """ + Constructs a TranscriptContext + + :param sid: A 34 character string that uniquely identifies this Transcript. + """ + return TranscriptContext(self._version, sid=sid) + + def __call__(self, sid: str) -> TranscriptContext: + """ + Constructs a TranscriptContext + + :param sid: A 34 character string that uniquely identifies this Transcript. + """ + return TranscriptContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" 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 new file mode 100644 index 0000000000..a4d08a488d --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/media.py @@ -0,0 +1,303 @@ +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 MediaInstance(InstanceResource): + """ + :ivar account_sid: The unique SID identifier of the Account. + :ivar media_url: Downloadable URL for media, if stored in Twilio AI. + :ivar service_sid: The unique SID identifier of the Service. + :ivar sid: The unique SID identifier of the Transcript. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.media_url: Optional[str] = payload.get("media_url") + self.service_sid: Optional[str] = payload.get("service_sid") + self.sid: Optional[str] = payload.get("sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "sid": sid, + } + + self._context: Optional[MediaContext] = None + + @property + def _proxy(self) -> "MediaContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: MediaContext for this MediaInstance + """ + if self._context is None: + self._context = MediaContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + 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 + """ + return self._proxy.fetch( + redacted=redacted, + ) + + 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 + """ + return await self._proxy.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MediaContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the MediaContext + + :param version: Version that contains the resource + :param sid: The unique SID identifier of the Transcript. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Transcripts/{sid}/Media".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) -> 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"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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) + """ + + 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 + ) -> 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class MediaList(ListResource): + + def __init__(self, version: Version, sid: str): + """ + Initialize the MediaList + + :param version: Version that contains the resource + :param sid: The unique SID identifier of the Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + + def get(self) -> MediaContext: + """ + Constructs a MediaContext + + """ + return MediaContext(self._version, sid=self._solution["sid"]) + + def __call__(self) -> MediaContext: + """ + Constructs a MediaContext + + """ + return MediaContext(self._version, sid=self._solution["sid"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/transcript/operator_result.py b/twilio/rest/intelligence/v2/transcript/operator_result.py new file mode 100644 index 0000000000..01af814a79 --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/operator_result.py @@ -0,0 +1,806 @@ +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, 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 OperatorResultInstance(InstanceResource): + + class OperatorType(object): + CONVERSATION_CLASSIFY = "conversation-classify" + UTTERANCE_CLASSIFY = "utterance-classify" + EXTRACT = "extract" + EXTRACT_NORMALIZE = "extract-normalize" + PII_EXTRACT = "pii-extract" + TEXT_GENERATION = "text-generation" + JSON = "json" + + """ + :ivar operator_type: + :ivar name: The name of the applied Language Understanding. + :ivar operator_sid: A 34 character string that identifies this Language Understanding operator sid. + :ivar extract_match: Boolean to tell if extract Language Understanding Processing model matches results. + :ivar match_probability: Percentage of 'matching' class needed to consider a sentence matches + :ivar normalized_result: Normalized output of extraction stage which matches Label. + :ivar utterance_results: List of mapped utterance object which matches sentences. + :ivar utterance_match: Boolean to tell if Utterance matches results. + :ivar predicted_label: The 'matching' class. This might be available on conversation classify model outputs. + :ivar predicted_probability: Percentage of 'matching' class needed to consider a sentence matches. + :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. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + transcript_sid: str, + operator_sid: Optional[str] = None, + ): + super().__init__(version) + + self.operator_type: Optional["OperatorResultInstance.OperatorType"] = ( + payload.get("operator_type") + ) + self.name: Optional[str] = payload.get("name") + self.operator_sid: Optional[str] = payload.get("operator_sid") + self.extract_match: Optional[bool] = payload.get("extract_match") + self.match_probability: Optional[float] = deserialize.decimal( + payload.get("match_probability") + ) + self.normalized_result: Optional[str] = payload.get("normalized_result") + self.utterance_results: Optional[List[Dict[str, object]]] = payload.get( + "utterance_results" + ) + self.utterance_match: Optional[bool] = payload.get("utterance_match") + self.predicted_label: Optional[str] = payload.get("predicted_label") + self.predicted_probability: Optional[float] = deserialize.decimal( + payload.get("predicted_probability") + ) + self.label_probabilities: Optional[Dict[str, object]] = payload.get( + "label_probabilities" + ) + self.extract_results: Optional[Dict[str, object]] = payload.get( + "extract_results" + ) + 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") + + self._solution = { + "transcript_sid": transcript_sid, + "operator_sid": operator_sid or self.operator_sid, + } + + 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, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + return self._context + + 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 + """ + return self._proxy.fetch( + redacted=redacted, + ) + + 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 + """ + return await self._proxy.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 + + :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, transcript_sid: str, operator_sid: str): + """ + Initialize the OperatorResultContext + + :param version: Version that contains the resource + :param transcript_sid: A 34 character string that uniquely identifies this Transcript. + :param operator_sid: A 34 character string that identifies this Language Understanding operator sid. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + "operator_sid": operator_sid, + } + self._uri = ( + "/Transcripts/{transcript_sid}/OperatorResults/{operator_sid}".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 + ) -> 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, + transcript_sid=self._solution["transcript_sid"], + operator_sid=self._solution["operator_sid"], + ) + + def fetch_with_http_info( + self, redacted: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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) + + 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 + ) -> 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, + transcript_sid=self._solution["transcript_sid"], + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class OperatorResultPage(Page): + + 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, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class OperatorResultList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the OperatorResultList + + :param version: Version that contains the resource + :param transcript_sid: A 34 character string that uniquely identifies this Transcript. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "transcript_sid": transcript_sid, + } + self._uri = "/Transcripts/{transcript_sid}/OperatorResults".format( + **self._solution + ) + + def stream( + self, + redacted: Union[bool, 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(redacted=redacted, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + redacted: Union[bool, 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(redacted=redacted, page_size=limits["page_size"]) + + 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, + 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 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: list that will contain up to limit results + """ + + return list( + self.stream( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + redacted: Union[bool, 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 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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + redacted=redacted, + limit=limit, + page_size=page_size, + ) + ] + + 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, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> OperatorResultPage: + """ + Retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :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: Page of OperatorResultInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return OperatorResultPage(self._version, response, solution=self._solution) + + async def page_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, + ) -> OperatorResultPage: + """ + Asynchronously retrieve a single page of OperatorResultInstance records from the API. + Request is executed immediately + + :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: Page of OperatorResultInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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: + """ + 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, solution=self._solution) + + 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, solution=self._solution) + + def get(self, operator_sid: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_sid: A 34 character string that identifies this Language Understanding operator sid. + """ + return OperatorResultContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + operator_sid=operator_sid, + ) + + def __call__(self, operator_sid: str) -> OperatorResultContext: + """ + Constructs a OperatorResultContext + + :param operator_sid: A 34 character string that identifies this Language Understanding operator sid. + """ + return OperatorResultContext( + self._version, + transcript_sid=self._solution["transcript_sid"], + operator_sid=operator_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v2/transcript/sentence.py b/twilio/rest/intelligence/v2/transcript/sentence.py new file mode 100644 index 0000000000..ee11548693 --- /dev/null +++ b/twilio/rest/intelligence/v2/transcript/sentence.py @@ -0,0 +1,556 @@ +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, 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 +from twilio.base.version import Version +from twilio.base.page import Page + + +class SentenceInstance(InstanceResource): + """ + :ivar media_channel: The channel number. + :ivar sentence_index: The index of the sentence in the transcript. + :ivar start_time: Offset from the beginning of the transcript when this sentence starts. + :ivar end_time: Offset from the beginning of the transcript when this sentence ends. + :ivar transcript: Transcript text. + :ivar sid: A 34 character string that uniquely identifies this Sentence. + :ivar confidence: + :ivar words: Detailed information for each of the words of the given Sentence. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], transcript_sid: str): + super().__init__(version) + + self.media_channel: Optional[int] = deserialize.integer( + payload.get("media_channel") + ) + self.sentence_index: Optional[int] = deserialize.integer( + payload.get("sentence_index") + ) + 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[str] = payload.get("confidence") + self.words: Optional[List[Dict[str, object]]] = payload.get("words") + + self._solution = { + "transcript_sid": transcript_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 SentencePage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> SentenceInstance: + """ + Build an instance of SentenceInstance + + :param payload: Payload response from the API + """ + + return SentenceInstance( + self._version, payload, transcript_sid=self._solution["transcript_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SentenceList(ListResource): + + def __init__(self, version: Version, transcript_sid: str): + """ + Initialize the SentenceList + + :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".format(**self._solution) + + def stream( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SentenceInstance]: + """ + Streams SentenceInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SentenceInstance]: + """ + Asynchronously streams SentenceInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + redacted=redacted, + word_timestamps=word_timestamps, + page_size=limits["page_size"], + ) + + 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, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SentenceInstance]: + """ + Lists SentenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + redacted: Union[bool, object] = values.unset, + word_timestamps: Union[bool, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SentenceInstance]: + """ + Asynchronously lists SentenceInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + redacted=redacted, + word_timestamps=word_timestamps, + limit=limit, + page_size=page_size, + ) + ] + + 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, + 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, + ) -> SentencePage: + """ + Retrieve a single page of SentenceInstance records from the API. + Request is executed immediately + + :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: Page of SentenceInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SentencePage(self._version, response, solution=self._solution) + + async def page_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, + ) -> SentencePage: + """ + Asynchronously retrieve a single page of SentenceInstance records from the API. + Request is executed immediately + + :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: Page of SentenceInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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: + """ + Retrieve a specific page of SentenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SentenceInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SentencePage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> SentencePage: + """ + Asynchronously retrieve a specific page of SentenceInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SentenceInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SentencePage(self._version, response, solution=self._solution) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/intelligence/v3/__init__.py b/twilio/rest/intelligence/v3/__init__.py new file mode 100644 index 0000000000..2e3f84bdf5 --- /dev/null +++ b/twilio/rest/intelligence/v3/__init__.py @@ -0,0 +1,82 @@ +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.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 + + @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 + + 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..0d99163014 --- /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. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :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. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :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. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :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. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :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. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :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. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :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. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :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. + :param datetime created_at_after: Filter by Conversations created after this timestamp. + :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. + :param created_at_after: Filter by Conversations created after this timestamp. + :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. + :param created_at_after: Filter by Conversations created after this timestamp. + :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. + :param created_at_after: Filter by Conversations created after this timestamp. + :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. + :param created_at_after: Filter by Conversations created after this timestamp. + :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..6306102919 --- /dev/null +++ b/twilio/rest/intelligence/v3/operator.py @@ -0,0 +1,1242 @@ +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.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: + 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/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/IpMessagingBase.py b/twilio/rest/ip_messaging/IpMessagingBase.py index d9e063c308..752d41adce 100644 --- a/twilio/rest/ip_messaging/IpMessagingBase.py +++ b/twilio/rest/ip_messaging/IpMessagingBase.py @@ -18,6 +18,7 @@ class IpMessagingBase(Domain): + def __init__(self, twilio: Client): """ Initialize the IpMessaging Domain diff --git a/twilio/rest/ip_messaging/v1/__init__.py b/twilio/rest/ip_messaging/v1/__init__.py index 1fd53b76b1..d1f40c791f 100644 --- a/twilio/rest/ip_messaging/v1/__init__.py +++ b/twilio/rest/ip_messaging/v1/__init__.py @@ -20,6 +20,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of IpMessaging diff --git a/twilio/rest/ip_messaging/v1/credential.py b/twilio/rest/ip_messaging/v1/credential.py index 6a193aa1f4..b363627051 100644 --- a/twilio/rest/ip_messaging/v1/credential.py +++ b/twilio/rest/ip_messaging/v1/credential.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class CredentialInstance(InstanceResource): + class PushService(object): GCM = "gcm" APN = "apn" @@ -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 @@ -185,6 +283,7 @@ def __repr__(self) -> str: class CredentialContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CredentialContext @@ -200,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 @@ -207,9 +320,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -219,9 +354,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance 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) -> CredentialInstance: @@ -231,17 +390,43 @@ def fetch(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialInstance: """ @@ -250,17 +435,63 @@ async def fetch_async(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + 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, + 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 update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def update( self, @@ -283,24 +514,83 @@ def update( :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( { "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -323,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -353,12 +666,14 @@ def __repr__(self) -> str: 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: @@ -371,6 +686,7 @@ def __repr__(self) -> str: class CredentialList(ListResource): + def __init__(self, version: Version): """ Initialize the CredentialList @@ -382,6 +698,44 @@ def __init__(self, version: Version): self._uri = "/Credentials" + def _create( + 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 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.PushService", @@ -405,25 +759,89 @@ def create( :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( { "Type": type, "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(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, @@ -448,25 +866,51 @@ async def create_async( :returns: The created CredentialInstance """ - data = values.of( - { - "Type": type, - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload) + :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, @@ -518,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, @@ -537,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -563,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( @@ -571,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, @@ -595,7 +1141,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CredentialPage(self._version, response) async def page_async( @@ -622,11 +1174,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 c07b4cc252..61c06df216 100644 --- a/twilio/rest/ip_messaging/v1/service/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class ServiceInstance(InstanceResource): - """ :ivar sid: :ivar account_sid: @@ -96,6 +95,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -131,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 @@ -149,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, @@ -497,120 +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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, @@ -666,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: @@ -725,76 +648,66 @@ def update( :param limits_channel_members: :param limits_user_channels: - :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": read_status_enabled, - "ReachabilityEnabled": reachability_enabled, - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": notifications_new_message_enabled, - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": notifications_added_to_channel_enabled, - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": notifications_removed_from_channel_enabled, - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": 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 = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, ) - 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, @@ -850,9 +763,9 @@ async def update_async( 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: """ - Asynchronous coroutine to update the ServiceInstance + Asynchronous coroutine to update the ServiceInstance with HTTP info :param friendly_name: :param default_service_role_sid: @@ -909,29 +822,863 @@ async def update_async( :param limits_channel_members: :param limits_user_channels: - :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": read_status_enabled, - "ReachabilityEnabled": reachability_enabled, - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": notifications_new_message_enabled, - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.AddedToChannel.Enabled": notifications_added_to_channel_enabled, - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.RemovedFromChannel.Enabled": notifications_removed_from_channel_enabled, - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.InvitedToChannel.Enabled": notifications_invited_to_channel_enabled, - "Notifications.InvitedToChannel.Template": notifications_invited_to_channel_template, - "PreWebhookUrl": pre_webhook_url, - "PostWebhookUrl": post_webhook_url, - "WebhookMethod": webhook_method, + 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, @@ -969,14 +1716,366 @@ async def update_async( "Limits.UserChannels": limits_user_channels, } ) + 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, + 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: + """ + 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_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, _, _ = 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"]) + + 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 + + :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, + :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: @@ -1025,12 +2124,14 @@ def __repr__(self) -> str: 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: @@ -1043,6 +2144,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -1054,50 +2156,100 @@ 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 - - :param friendly_name: + Internal helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_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, + 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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -1148,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, @@ -1167,6 +2369,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -1193,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( @@ -1201,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, @@ -1225,7 +2479,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -1252,11 +2512,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 32961bcff0..bca3bc717b 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/channel/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,6 +27,7 @@ class ChannelInstance(InstanceResource): + class ChannelType(object): PUBLIC = "public" PRIVATE = "private" @@ -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: """ @@ -212,6 +292,7 @@ def __repr__(self) -> str: class ChannelContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the ChannelContext @@ -233,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 @@ -240,9 +335,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -252,9 +369,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ChannelInstance 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) -> ChannelInstance: @@ -264,18 +405,45 @@ def fetch(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ChannelInstance: """ @@ -284,34 +452,43 @@ async def fetch_async(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ChannelInstance( + 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( + 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 - - :param friendly_name: - :param unique_name: - :param attributes: + Internal helper for update operation - :returns: The updated ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -319,13 +496,34 @@ def update( "Attributes": attributes, } ) + 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, + 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, @@ -333,21 +531,45 @@ 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( { "FriendlyName": friendly_name, @@ -355,13 +577,34 @@ async def update_async( "Attributes": attributes, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -369,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: """ @@ -419,12 +688,14 @@ def __repr__(self) -> str: class ChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ Build an instance of ChannelInstance :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -439,6 +710,7 @@ def __repr__(self) -> str: class ChannelList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the ChannelList @@ -455,6 +727,38 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Channels".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "Attributes": attributes, + "Type": type, + } + ) + 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, @@ -472,6 +776,58 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, @@ -480,15 +836,14 @@ def create( "Type": type, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ChannelInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -508,24 +863,43 @@ async def create_async( :returns: The created ChannelInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Attributes": attributes, - "Type": type, - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + attributes=attributes, + type=type, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return ChannelInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return ChannelInstance( + 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, @@ -581,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, @@ -602,6 +1032,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -631,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( @@ -640,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, @@ -667,8 +1155,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ChannelPage(self._version, response, self._solution) + 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 ChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -697,10 +1191,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ChannelPage(self._version, response, self._solution) + 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: """ @@ -712,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: """ @@ -724,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 476e89f4c2..f0b7e70c47 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v1/service/channel/invite.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class InviteInstance(InstanceResource): - """ :ivar sid: :ivar account_sid: @@ -68,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -105,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 @@ -123,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 @@ -134,6 +170,7 @@ def __repr__(self) -> str: class InviteContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the InviteContext @@ -157,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 @@ -164,9 +215,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -176,9 +249,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance 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) -> InviteInstance: @@ -188,19 +285,47 @@ def fetch(self) -> InviteInstance: :returns: The fetched InviteInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return InviteInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> InviteInstance: """ @@ -209,19 +334,31 @@ async def fetch_async(self) -> InviteInstance: :returns: The fetched InviteInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return InviteInstance( + 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: """ @@ -234,12 +371,14 @@ def __repr__(self) -> str: class InvitePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: """ Build an instance of InviteInstance :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -257,6 +396,7 @@ def __repr__(self) -> str: class InviteList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the InviteList @@ -277,30 +417,44 @@ 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( { "Identity": identity, "RoleSid": role_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -308,30 +462,66 @@ 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( { "Identity": identity, "RoleSid": role_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, + 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, @@ -339,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, @@ -393,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, @@ -414,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -443,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( @@ -452,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, @@ -479,8 +805,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return InvitePage(self._version, response, self._solution) + 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 InvitePage(self._version, response, solution=self._solution) async def page_async( self, @@ -509,10 +841,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return InvitePage(self._version, response, self._solution) + 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: """ @@ -524,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: """ @@ -536,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 2414e72c93..6dccde7822 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/member.py +++ b/twilio/rest/ip_messaging/v1/service/channel/member.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class MemberInstance(InstanceResource): - """ :ivar sid: :ivar account_sid: @@ -64,9 +63,9 @@ def __init__( self.last_consumed_message_index: Optional[int] = deserialize.integer( payload.get("last_consumed_message_index") ) - self.last_consumption_timestamp: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) self.url: Optional[str] = payload.get("url") self._solution = { @@ -74,6 +73,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[MemberContext] = None @property @@ -111,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 @@ -129,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, @@ -165,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 @@ -176,6 +248,7 @@ def __repr__(self) -> str: class MemberContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the MemberContext @@ -199,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 @@ -206,9 +293,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -218,9 +327,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MemberInstance 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) -> MemberInstance: @@ -230,19 +363,47 @@ def fetch(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MemberInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MemberInstance: """ @@ -251,46 +412,76 @@ async def fetch_async(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MemberInstance( + 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( + 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( { "RoleSid": role_sid, "LastConsumedMessageIndex": last_consumed_message_index, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -299,32 +490,75 @@ 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( { "RoleSid": role_sid, "LastConsumedMessageIndex": last_consumed_message_index, } ) + 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, + 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, @@ -333,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 @@ -344,12 +603,14 @@ def __repr__(self) -> str: class MemberPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: """ Build an instance of MemberInstance :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -367,6 +628,7 @@ def __repr__(self) -> str: class MemberList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the MemberList @@ -387,30 +649,44 @@ 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( { "Identity": identity, "RoleSid": role_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -418,30 +694,66 @@ 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( { "Identity": identity, "RoleSid": role_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -449,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, @@ -503,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, @@ -524,6 +914,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -553,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( @@ -562,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, @@ -589,8 +1037,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MemberPage(self._version, response, self._solution) + 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 MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -619,10 +1073,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MemberPage(self._version, response, self._solution) + 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: """ @@ -634,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: """ @@ -646,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 e562faafb6..6d0ba2da88 100644 --- a/twilio/rest/ip_messaging/v1/service/channel/message.py +++ b/twilio/rest/ip_messaging/v1/service/channel/message.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class MessageInstance(InstanceResource): + class OrderType(object): ASC = "asc" DESC = "desc" @@ -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 @@ -179,6 +253,7 @@ def __repr__(self) -> str: class MessageContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the MessageContext @@ -202,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 @@ -209,9 +298,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -221,9 +332,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessageInstance 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) -> MessageInstance: @@ -233,19 +368,47 @@ def fetch(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MessageInstance: """ @@ -254,46 +417,74 @@ async def fetch_async(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + 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( + 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( { "Body": body, "Attributes": attributes, } ) + 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, + 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, @@ -302,32 +493,71 @@ 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( { "Body": body, "Attributes": attributes, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -336,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 @@ -347,12 +602,14 @@ def __repr__(self) -> str: 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, @@ -370,6 +627,7 @@ def __repr__(self) -> str: class MessageList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the MessageList @@ -390,21 +648,19 @@ 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( { "Body": body, @@ -412,13 +668,32 @@ def create( "Attributes": attributes, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -426,21 +701,45 @@ 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( { "Body": body, @@ -448,13 +747,34 @@ async def create_async( "Attributes": attributes, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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: 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, @@ -462,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, @@ -516,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, @@ -537,6 +939,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -566,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( @@ -575,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, @@ -602,8 +1062,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MessagePage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -632,10 +1098,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MessagePage(self._version, response, self._solution) + 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: """ @@ -647,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: """ @@ -659,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 e637e2c900..e7156129ef 100644 --- a/twilio/rest/ip_messaging/v1/service/role.py +++ b/twilio/rest/ip_messaging/v1/service/role.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class RoleInstance(InstanceResource): + class RoleType(object): CHANNEL = "channel" DEPLOYMENT = "deployment" @@ -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 @@ -156,6 +218,7 @@ def __repr__(self) -> str: class RoleContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the RoleContext @@ -173,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 @@ -180,9 +257,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -192,9 +291,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance 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) -> RoleInstance: @@ -204,18 +327,45 @@ def fetch(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return RoleInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RoleInstance: """ @@ -224,12 +374,7 @@ async def fetch_async(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -237,26 +382,54 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance( self._version, payload, @@ -264,26 +437,55 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -291,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 @@ -302,12 +521,14 @@ def __repr__(self) -> str: class RolePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: """ Build an instance of RoleInstance :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -322,6 +543,7 @@ def __repr__(self) -> str: class RoleList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the RoleList @@ -338,6 +560,33 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: 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.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: @@ -350,6 +599,43 @@ def create( :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"] + ) + + 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: + :param type: + :param permission: + + :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( { "FriendlyName": friendly_name, @@ -357,15 +643,14 @@ def create( "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RoleInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -380,23 +665,32 @@ async def create_async( :returns: The created RoleInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Permission": serialize.map(permission, lambda e: e), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return RoleInstance( + 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, @@ -448,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, @@ -467,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -493,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( @@ -501,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, @@ -525,8 +921,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RolePage(self._version, response, self._solution) + 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 RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -552,10 +954,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RolePage(self._version, response, self._solution) + 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: """ @@ -567,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: """ @@ -579,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 e19eb82be6..a428c09856 100644 --- a/twilio/rest/ip_messaging/v1/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v1/service/user/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class UserInstance(InstanceResource): - """ :ivar sid: :ivar account_sid: @@ -77,6 +76,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[UserContext] = None @property @@ -113,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 @@ -131,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, @@ -173,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: """ @@ -191,6 +269,7 @@ def __repr__(self) -> str: class UserContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the UserContext @@ -210,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 @@ -217,9 +310,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -229,9 +344,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch(self) -> UserInstance: @@ -241,18 +380,45 @@ def fetch(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserInstance: """ @@ -261,34 +427,43 @@ async def fetch_async(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + 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( + 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( { "RoleSid": role_sid, @@ -296,13 +471,34 @@ def update( "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -310,21 +506,45 @@ 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( { "RoleSid": role_sid, @@ -332,13 +552,34 @@ async def update_async( "FriendlyName": friendly_name, } ) + 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, + 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, @@ -346,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: """ @@ -370,12 +637,14 @@ def __repr__(self) -> str: 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, service_sid=self._solution["service_sid"] ) @@ -390,6 +659,7 @@ def __repr__(self) -> str: class UserList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the UserList @@ -406,6 +676,38 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Users".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Identity": identity, + "RoleSid": role_sid, + "Attributes": attributes, + "FriendlyName": friendly_name, + } + ) + 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, identity: str, @@ -423,6 +725,58 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "Identity": identity, @@ -431,15 +785,14 @@ def create( "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return UserInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -459,24 +812,43 @@ async def create_async( :returns: The created UserInstance """ - data = values.of( - { - "Identity": identity, - "RoleSid": role_sid, - "Attributes": attributes, - "FriendlyName": friendly_name, - } + payload, _, _ = await self._create_async( + identity=identity, + role_sid=role_sid, + attributes=attributes, + friendly_name=friendly_name, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return UserInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return UserInstance( + 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, @@ -528,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, @@ -547,6 +969,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -573,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( @@ -581,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, @@ -605,8 +1079,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserPage(self._version, response, self._solution) + 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 UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -632,10 +1112,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserPage(self._version, response, self._solution) + 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: """ @@ -647,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: """ @@ -659,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 4d00fa50c0..28ee7b4930 100644 --- a/twilio/rest/ip_messaging/v1/service/user/user_channel.py +++ b/twilio/rest/ip_messaging/v1/service/user/user_channel.py @@ -12,9 +12,9 @@ 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 @@ -23,6 +23,7 @@ class UserChannelInstance(InstanceResource): + class ChannelStatus(object): JOINED = "joined" INVITED = "invited" @@ -75,12 +76,14 @@ def __repr__(self) -> str: class UserChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: """ Build an instance of UserChannelInstance :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -98,6 +101,7 @@ def __repr__(self) -> str: class UserChannelList(ListResource): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ Initialize the UserChannelList @@ -168,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, @@ -187,6 +241,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -213,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( @@ -221,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, @@ -245,8 +351,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserChannelPage(self._version, response, self._solution) + 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 UserChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -272,10 +384,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserChannelPage(self._version, response, self._solution) + 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: """ @@ -287,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: """ @@ -299,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/__init__.py b/twilio/rest/ip_messaging/v2/__init__.py index 966a35a441..6003c86b12 100644 --- a/twilio/rest/ip_messaging/v2/__init__.py +++ b/twilio/rest/ip_messaging/v2/__init__.py @@ -20,6 +20,7 @@ class V2(Version): + def __init__(self, domain: Domain): """ Initialize the V2 version of IpMessaging diff --git a/twilio/rest/ip_messaging/v2/credential.py b/twilio/rest/ip_messaging/v2/credential.py index 3d72b3a0d6..7032a6e2f3 100644 --- a/twilio/rest/ip_messaging/v2/credential.py +++ b/twilio/rest/ip_messaging/v2/credential.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class CredentialInstance(InstanceResource): + class PushService(object): GCM = "gcm" APN = "apn" @@ -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 @@ -185,6 +283,7 @@ def __repr__(self) -> str: class CredentialContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CredentialContext @@ -200,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 @@ -207,9 +320,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -219,9 +354,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance 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) -> CredentialInstance: @@ -231,17 +390,43 @@ def fetch(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialInstance: """ @@ -250,17 +435,63 @@ async def fetch_async(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + 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, + 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 update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def update( self, @@ -283,24 +514,83 @@ def update( :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( { "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -323,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -353,12 +666,14 @@ def __repr__(self) -> str: 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: @@ -371,6 +686,7 @@ def __repr__(self) -> str: class CredentialList(ListResource): + def __init__(self, version: Version): """ Initialize the CredentialList @@ -382,6 +698,44 @@ def __init__(self, version: Version): self._uri = "/Credentials" + def _create( + 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 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.PushService", @@ -405,25 +759,89 @@ def create( :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( { "Type": type, "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(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, @@ -448,25 +866,51 @@ async def create_async( :returns: The created CredentialInstance """ - data = values.of( - { - "Type": type, - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload) + :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, @@ -518,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, @@ -537,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -563,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( @@ -571,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, @@ -595,7 +1141,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CredentialPage(self._version, response) async def page_async( @@ -622,11 +1174,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 b94def1fa6..a00dfed962 100644 --- a/twilio/rest/ip_messaging/v2/service/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/__init__.py @@ -12,10 +12,10 @@ 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 @@ -28,7 +28,6 @@ class ServiceInstance(InstanceResource): - """ :ivar sid: :ivar account_sid: @@ -105,6 +104,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -140,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 @@ -158,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, @@ -372,128 +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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, @@ -528,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: @@ -564,53 +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": read_status_enabled, - "ReachabilityEnabled": reachability_enabled, - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": notifications_new_message_enabled, - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.NewMessage.Sound": notifications_new_message_sound, - "Notifications.NewMessage.BadgeCountEnabled": notifications_new_message_badge_count_enabled, - "Notifications.AddedToChannel.Enabled": notifications_added_to_channel_enabled, - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, - "Notifications.RemovedFromChannel.Enabled": notifications_removed_from_channel_enabled, - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, - "Notifications.InvitedToChannel.Enabled": 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": notifications_log_enabled, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, @@ -645,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: @@ -681,75 +586,921 @@ async def update_async( :param post_webhook_retry_count: :param notifications_log_enabled: - :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": read_status_enabled, - "ReachabilityEnabled": reachability_enabled, - "TypingIndicatorTimeout": typing_indicator_timeout, - "ConsumptionReportInterval": consumption_report_interval, - "Notifications.NewMessage.Enabled": notifications_new_message_enabled, - "Notifications.NewMessage.Template": notifications_new_message_template, - "Notifications.NewMessage.Sound": notifications_new_message_sound, - "Notifications.NewMessage.BadgeCountEnabled": notifications_new_message_badge_count_enabled, - "Notifications.AddedToChannel.Enabled": notifications_added_to_channel_enabled, - "Notifications.AddedToChannel.Template": notifications_added_to_channel_template, - "Notifications.AddedToChannel.Sound": notifications_added_to_channel_sound, - "Notifications.RemovedFromChannel.Enabled": notifications_removed_from_channel_enabled, - "Notifications.RemovedFromChannel.Template": notifications_removed_from_channel_template, - "Notifications.RemovedFromChannel.Sound": notifications_removed_from_channel_sound, - "Notifications.InvitedToChannel.Enabled": 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": notifications_log_enabled, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def bindings(self) -> BindingList: - """ - Access the bindings - """ - if self._bindings is None: - self._bindings = BindingList( - self._version, - self._solution["sid"], - ) - return self._bindings - - @property - def channels(self) -> ChannelList: + :returns: ApiResponse with instance, status code, and headers """ - Access the channels - """ - if self._channels is None: - self._channels = ChannelList( - self._version, - self._solution["sid"], - ) - return self._channels + 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 + ), + "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 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: + + :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, + ) + 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, + self._solution["sid"], + ) + return self._bindings + + @property + def channels(self) -> ChannelList: + """ + Access the channels + """ + if self._channels is None: + self._channels = ChannelList( + self._version, + self._solution["sid"], + ) + return self._channels @property def roles(self) -> RoleList: @@ -786,12 +1537,14 @@ def __repr__(self) -> str: 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: @@ -804,6 +1557,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -815,50 +1569,100 @@ 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 - - :param friendly_name: + Internal helper for create operation - :returns: The created ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_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, + 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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -909,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, @@ -928,6 +1782,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -954,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( @@ -962,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, @@ -986,7 +1892,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -1013,11 +1925,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 70dbc78fb7..b7394ff7a1 100644 --- a/twilio/rest/ip_messaging/v2/service/binding.py +++ b/twilio/rest/ip_messaging/v2/service/binding.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class BindingInstance(InstanceResource): + class BindingType(object): GCM = "gcm" APN = "apn" @@ -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 @@ -141,6 +179,7 @@ def __repr__(self) -> str: class BindingContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the BindingContext @@ -158,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 @@ -165,9 +218,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -177,9 +252,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance 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) -> BindingInstance: @@ -189,18 +288,45 @@ def fetch(self) -> BindingInstance: :returns: The fetched BindingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return BindingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> BindingInstance: """ @@ -209,18 +335,29 @@ async def fetch_async(self) -> BindingInstance: :returns: The fetched BindingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return BindingInstance( + 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: """ @@ -233,12 +370,14 @@ def __repr__(self) -> str: class BindingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: """ Build an instance of BindingInstance :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -253,6 +392,7 @@ def __repr__(self) -> str: class BindingList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the BindingList @@ -331,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, @@ -354,6 +554,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -386,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( @@ -396,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, @@ -426,8 +690,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return BindingPage(self._version, response, self._solution) + 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 BindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -459,10 +729,96 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return BindingPage(self._version, response, self._solution) + 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: """ @@ -474,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: """ @@ -486,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 6e62c31093..5dd5288a73 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/channel/__init__.py @@ -12,10 +12,10 @@ 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 @@ -28,6 +28,7 @@ class ChannelInstance(InstanceResource): + class ChannelType(object): PUBLIC = "public" PRIVATE = "private" @@ -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: """ @@ -268,6 +392,7 @@ def __repr__(self) -> str: class ChannelContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the ChannelContext @@ -290,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[ @@ -303,13 +452,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -324,14 +510,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> ChannelInstance: @@ -341,18 +556,45 @@ def fetch(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ChannelInstance: """ @@ -361,20 +603,31 @@ async def fetch_async(self) -> ChannelInstance: :returns: The fetched ChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ChannelInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -385,20 +638,14 @@ 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 + Internal helper for update operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -409,24 +656,26 @@ def update( "CreatedBy": created_by, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return ChannelInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "ChannelInstance.WebhookEnabledType", object @@ -439,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: @@ -451,26 +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( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - - 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, @@ -478,15 +716,188 @@ 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, - self._solution["service_sid"], + 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"], ) return self._invites @@ -541,12 +952,14 @@ def __repr__(self) -> str: class ChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ChannelInstance: """ Build an instance of ChannelInstance :param payload: Payload response from the API """ + return ChannelInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -561,6 +974,7 @@ def __repr__(self) -> str: class ChannelList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the ChannelList @@ -577,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 @@ -589,21 +1003,14 @@ 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 - - :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: + Internal helper for create operation - :returns: The created ChannelInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -618,17 +1025,60 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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[ + "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 @@ -640,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: @@ -653,8 +1103,43 @@ 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( { "FriendlyName": friendly_name, @@ -669,16 +1154,101 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -733,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, @@ -754,6 +1380,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( type=type, @@ -783,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( @@ -792,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, @@ -819,8 +1503,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ChannelPage(self._version, response, self._solution) + 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 ChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -849,10 +1539,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ChannelPage(self._version, response, self._solution) + 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: """ @@ -864,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: """ @@ -876,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 aeb07b7b92..3faf373020 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/invite.py +++ b/twilio/rest/ip_messaging/v2/service/channel/invite.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class InviteInstance(InstanceResource): - """ :ivar sid: :ivar account_sid: @@ -68,6 +67,7 @@ def __init__( "channel_sid": channel_sid, "sid": sid or self.sid, } + self._context: Optional[InviteContext] = None @property @@ -105,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 @@ -123,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 @@ -134,6 +170,7 @@ def __repr__(self) -> str: class InviteContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the InviteContext @@ -157,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 @@ -164,9 +215,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -176,9 +249,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InviteInstance 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) -> InviteInstance: @@ -188,19 +285,47 @@ def fetch(self) -> InviteInstance: :returns: The fetched InviteInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return InviteInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InviteInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> InviteInstance: """ @@ -209,19 +334,31 @@ async def fetch_async(self) -> InviteInstance: :returns: The fetched InviteInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return InviteInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return InviteInstance( + 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: """ @@ -234,12 +371,14 @@ def __repr__(self) -> str: class InvitePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InviteInstance: """ Build an instance of InviteInstance :param payload: Payload response from the API """ + return InviteInstance( self._version, payload, @@ -257,6 +396,7 @@ def __repr__(self) -> str: class InviteList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the InviteList @@ -277,30 +417,44 @@ 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( { "Identity": identity, "RoleSid": role_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -308,30 +462,66 @@ 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( { "Identity": identity, "RoleSid": role_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, + 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, @@ -339,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, @@ -393,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, @@ -414,6 +682,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -443,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( @@ -452,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, @@ -479,8 +805,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return InvitePage(self._version, response, self._solution) + 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 InvitePage(self._version, response, solution=self._solution) async def page_async( self, @@ -509,10 +841,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return InvitePage(self._version, response, self._solution) + 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: """ @@ -524,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: """ @@ -536,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 823c37b6df..580bbbe1a4 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/member.py +++ b/twilio/rest/ip_messaging/v2/service/channel/member.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class MemberInstance(InstanceResource): + class WebhookEnabledType(object): TRUE = "true" FALSE = "false" @@ -68,9 +69,9 @@ def __init__( self.last_consumed_message_index: Optional[int] = deserialize.integer( payload.get("last_consumed_message_index") ) - self.last_consumption_timestamp: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + self.last_consumption_timestamp: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("last_consumption_timestamp")) + ) self.url: Optional[str] = payload.get("url") self.attributes: Optional[str] = payload.get("attributes") @@ -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 @@ -231,6 +355,7 @@ def __repr__(self) -> str: class MemberContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the MemberContext @@ -254,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[ @@ -267,13 +416,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -288,14 +474,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> MemberInstance: @@ -305,19 +520,47 @@ def fetch(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MemberInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MemberInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MemberInstance: """ @@ -326,21 +569,33 @@ async def fetch_async(self) -> MemberInstance: :returns: The fetched MemberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MemberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MemberInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "MemberInstance.WebhookEnabledType", object @@ -351,20 +606,14 @@ 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( { "RoleSid": role_sid, @@ -377,25 +626,26 @@ def update( "Attributes": attributes, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return MemberInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MemberInstance.WebhookEnabledType", object @@ -408,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: @@ -420,28 +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( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - - 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, @@ -450,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 """ @@ -461,12 +876,14 @@ def __repr__(self) -> str: class MemberPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MemberInstance: """ Build an instance of MemberInstance :param payload: Payload response from the API """ + return MemberInstance( self._version, payload, @@ -484,6 +901,7 @@ def __repr__(self) -> str: class MemberList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the MemberList @@ -504,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[ @@ -516,21 +934,14 @@ 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( { "Identity": identity, @@ -547,12 +958,55 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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, + 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, @@ -560,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[ @@ -572,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 @@ -585,8 +1039,46 @@ 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( { "Identity": identity, @@ -603,12 +1095,55 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -616,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, @@ -670,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, @@ -691,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( identity=identity, @@ -720,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( @@ -729,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, @@ -756,8 +1450,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MemberPage(self._version, response, self._solution) + 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 MemberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -786,10 +1486,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MemberPage(self._version, response, self._solution) + 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: """ @@ -801,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: """ @@ -813,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 c2401c53f9..f53ed8a70b 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/message.py +++ b/twilio/rest/ip_messaging/v2/service/channel/message.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class MessageInstance(InstanceResource): + class OrderType(object): ASC = "asc" DESC = "desc" @@ -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 @@ -239,6 +363,7 @@ def __repr__(self) -> str: class MessageContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the MessageContext @@ -262,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[ @@ -275,13 +424,50 @@ 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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, @@ -296,14 +482,43 @@ 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 - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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 + + :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 = 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: + 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) -> MessageInstance: @@ -313,19 +528,47 @@ def fetch(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MessageInstance: """ @@ -334,21 +577,33 @@ async def fetch_async(self) -> MessageInstance: :returns: The fetched MessageInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return MessageInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return MessageInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -359,20 +614,14 @@ 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( { "Body": body, @@ -383,25 +632,26 @@ def update( "From": from_, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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 - return MessageInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], + 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 ) - async def update_async( + def update( self, x_twilio_webhook_enabled: Union[ "MessageInstance.WebhookEnabledType", object @@ -414,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: @@ -426,26 +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( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) - - 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, @@ -454,23 +693,201 @@ 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) 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, @@ -488,6 +905,7 @@ def __repr__(self) -> str: class MessageList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the MessageList @@ -508,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 @@ -520,21 +938,14 @@ 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 - - :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: + Internal helper for create operation - :returns: The created MessageInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "From": from_, @@ -549,12 +960,55 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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[ + "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, @@ -562,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 @@ -574,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_: @@ -587,8 +1041,46 @@ 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( { "From": from_, @@ -603,12 +1095,55 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -616,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, @@ -670,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, @@ -691,6 +1327,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -720,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( @@ -729,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, @@ -756,8 +1450,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MessagePage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -786,10 +1486,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MessagePage(self._version, response, self._solution) + 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: """ @@ -801,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: """ @@ -813,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 077bbfa8e4..a72375bb7a 100644 --- a/twilio/rest/ip_messaging/v2/service/channel/webhook.py +++ b/twilio/rest/ip_messaging/v2/service/channel/webhook.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class WebhookInstance(InstanceResource): + class Method(object): GET = "GET" POST = "POST" @@ -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 @@ -200,6 +298,7 @@ def __repr__(self) -> str: class WebhookContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, channel_sid: str, sid: str): """ Initialize the WebhookContext @@ -223,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 @@ -230,9 +343,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -242,9 +377,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance 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) -> WebhookInstance: @@ -254,19 +413,47 @@ def fetch(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WebhookInstance: """ @@ -275,21 +462,33 @@ async def fetch_async(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + 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( + def _update( self, configuration_url: Union[str, object] = values.unset, configuration_method: Union["WebhookInstance.Method", object] = values.unset, @@ -297,19 +496,14 @@ 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 - - :param configuration_url: - :param configuration_method: - :param configuration_filters: - :param configuration_triggers: - :param configuration_flow_sid: - :param configuration_retry_count: + Internal helper for update operation - :returns: The updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Configuration.Url": configuration_url, @@ -324,13 +518,45 @@ def update( "Configuration.RetryCount": configuration_retry_count, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -339,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, @@ -347,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: @@ -358,8 +584,41 @@ 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( { "Configuration.Url": configuration_url, @@ -374,48 +633,120 @@ async def update_async( "Configuration.RetryCount": configuration_retry_count, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WebhookInstance( - self._version, - payload, - service_sid=self._solution["service_sid"], - channel_sid=self._solution["channel_sid"], - sid=self._solution["sid"], - ) + headers["Accept"] = "application/json" - def __repr__(self) -> str: - """ - Provide a friendly representation + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :returns: Machine friendly representation + 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: """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - + Asynchronous coroutine to update the WebhookInstance -class WebhookPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: - """ - Build an instance of WebhookInstance + :param configuration_url: + :param configuration_method: + :param configuration_filters: + :param configuration_triggers: + :param configuration_flow_sid: + :param configuration_retry_count: - :param payload: Payload response from the API + :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, service_sid=self._solution["service_sid"], channel_sid=self._solution["channel_sid"], + sid=self._solution["sid"], ) - def __repr__(self) -> str: - """ - Provide a friendly representation + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class WebhookPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: + """ + Build an instance of WebhookInstance + + :param payload: Payload response from the API + """ + + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + channel_sid=self._solution["channel_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation :returns: Machine friendly representation """ @@ -423,6 +754,7 @@ def __repr__(self) -> str: class WebhookList(ListResource): + def __init__(self, version: Version, service_sid: str, channel_sid: str): """ Initialize the WebhookList @@ -443,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, @@ -452,20 +784,14 @@ 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( { "Type": type, @@ -481,13 +807,48 @@ def create( "Configuration.RetryCount": configuration_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, + 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, @@ -495,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, @@ -504,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: @@ -516,8 +877,42 @@ 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( { "Type": type, @@ -533,13 +928,48 @@ async def create_async( "Configuration.RetryCount": configuration_retry_count, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -547,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, @@ -597,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, @@ -616,6 +1136,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -642,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( @@ -650,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, @@ -674,8 +1246,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return WebhookPage(self._version, response, self._solution) + 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 WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -701,10 +1279,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return WebhookPage(self._version, response, self._solution) + 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: """ @@ -716,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: """ @@ -728,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 c8e3b95611..02f3e055e0 100644 --- a/twilio/rest/ip_messaging/v2/service/role.py +++ b/twilio/rest/ip_messaging/v2/service/role.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class RoleInstance(InstanceResource): + class RoleType(object): CHANNEL = "channel" DEPLOYMENT = "deployment" @@ -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 @@ -156,6 +218,7 @@ def __repr__(self) -> str: class RoleContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the RoleContext @@ -173,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 @@ -180,9 +257,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -192,9 +291,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoleInstance 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) -> RoleInstance: @@ -204,18 +327,45 @@ def fetch(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RoleInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return RoleInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoleInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RoleInstance: """ @@ -224,12 +374,7 @@ async def fetch_async(self) -> RoleInstance: :returns: The fetched RoleInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return RoleInstance( self._version, payload, @@ -237,26 +382,54 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, permission: List[str]) -> RoleInstance: + """ + Update the RoleInstance + + :param permission: + + :returns: The updated RoleInstance + """ + payload, _, _ = self._update(permission=permission) return RoleInstance( self._version, payload, @@ -264,26 +437,55 @@ 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( { "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -291,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 @@ -302,12 +521,14 @@ def __repr__(self) -> str: class RolePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RoleInstance: """ Build an instance of RoleInstance :param payload: Payload response from the API """ + return RoleInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -322,6 +543,7 @@ def __repr__(self) -> str: class RoleList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the RoleList @@ -338,6 +560,33 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Roles".format(**self._solution) + def _create( + self, friendly_name: str, type: "RoleInstance.RoleType", permission: List[str] + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Permission": serialize.map(permission, lambda e: 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.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: @@ -350,6 +599,43 @@ def create( :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"] + ) + + 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: + :param type: + :param permission: + + :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( { "FriendlyName": friendly_name, @@ -357,15 +643,14 @@ def create( "Permission": serialize.map(permission, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RoleInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -380,23 +665,32 @@ async def create_async( :returns: The created RoleInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Permission": serialize.map(permission, lambda e: e), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, permission=permission ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return RoleInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return RoleInstance( + 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, @@ -448,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, @@ -467,6 +811,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -493,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( @@ -501,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, @@ -525,8 +921,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RolePage(self._version, response, self._solution) + 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 RolePage(self._version, response, solution=self._solution) async def page_async( self, @@ -552,10 +954,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RolePage(self._version, response, self._solution) + 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: """ @@ -567,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: """ @@ -579,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 1f11793877..b6eb03d7f4 100644 --- a/twilio/rest/ip_messaging/v2/service/user/__init__.py +++ b/twilio/rest/ip_messaging/v2/service/user/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,6 +26,7 @@ class UserInstance(InstanceResource): + class WebhookEnabledType(object): TRUE = "true" FALSE = "false" @@ -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: """ @@ -212,6 +302,7 @@ def __repr__(self) -> str: class UserContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the UserContext @@ -232,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 @@ -239,9 +344,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -251,9 +378,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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/json" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch(self) -> UserInstance: @@ -263,18 +414,45 @@ def fetch(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserInstance: """ @@ -283,20 +461,31 @@ async def fetch_async(self) -> UserInstance: :returns: The fetched UserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return UserInstance( + 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( + def _update( self, x_twilio_webhook_enabled: Union[ "UserInstance.WebhookEnabledType", object @@ -304,17 +493,14 @@ 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( { "RoleSid": role_sid, @@ -322,16 +508,50 @@ def update( "FriendlyName": friendly_name, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + headers = values.of({}) - payload = self._version.update( + 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 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, @@ -339,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 @@ -347,17 +567,47 @@ 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( { "RoleSid": role_sid, @@ -365,16 +615,50 @@ async def update_async( "FriendlyName": friendly_name, } ) - headers = values.of( - { - "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, - } - ) + 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" - payload = await self._version.update_async( + 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[ + "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, @@ -382,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: """ @@ -419,12 +736,14 @@ def __repr__(self) -> str: 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, service_sid=self._solution["service_sid"] ) @@ -439,6 +758,7 @@ def __repr__(self) -> str: class UserList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the UserList @@ -455,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[ @@ -464,18 +784,14 @@ 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 - - :param identity: - :param x_twilio_webhook_enabled: The X-Twilio-Webhook-Enabled HTTP request header - :param role_sid: - :param attributes: - :param friendly_name: + Internal helper for create operation - :returns: The created UserInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Identity": identity, @@ -487,17 +803,51 @@ def create( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = self._version.create( + + 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, + 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[ @@ -506,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 @@ -516,8 +866,37 @@ 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( { "Identity": identity, @@ -529,16 +908,83 @@ async def create_async( headers = values.of( { "X-Twilio-Webhook-Enabled": x_twilio_webhook_enabled, + "Content-Type": "application/x-www-form-urlencoded", } ) - payload = await self._version.create_async( + + 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, + 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, @@ -589,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, @@ -608,6 +1104,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -634,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( @@ -642,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, @@ -666,8 +1214,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserPage(self._version, response, self._solution) + 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 UserPage(self._version, response, solution=self._solution) async def page_async( self, @@ -693,10 +1247,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserPage(self._version, response, self._solution) + 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: """ @@ -708,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: """ @@ -720,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 c2e389fc92..cf7b3f7fc9 100644 --- a/twilio/rest/ip_messaging/v2/service/user/user_binding.py +++ b/twilio/rest/ip_messaging/v2/service/user/user_binding.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class UserBindingInstance(InstanceResource): + class BindingType(object): GCM = "gcm" APN = "apn" @@ -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 @@ -144,6 +182,7 @@ def __repr__(self) -> str: class UserBindingContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, user_sid: str, sid: str): """ Initialize the UserBindingContext @@ -165,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 @@ -172,9 +225,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -184,9 +259,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserBindingInstance 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) -> UserBindingInstance: @@ -196,19 +295,47 @@ def fetch(self) -> UserBindingInstance: :returns: The fetched UserBindingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], ) - return UserBindingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserBindingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserBindingInstance: """ @@ -217,19 +344,31 @@ async def fetch_async(self) -> UserBindingInstance: :returns: The fetched UserBindingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserBindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + sid=self._solution["sid"], ) - return UserBindingInstance( + 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: """ @@ -242,12 +381,14 @@ def __repr__(self) -> str: class UserBindingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UserBindingInstance: """ Build an instance of UserBindingInstance :param payload: Payload response from the API """ + return UserBindingInstance( self._version, payload, @@ -265,6 +406,7 @@ def __repr__(self) -> str: class UserBindingList(ListResource): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ Initialize the UserBindingList @@ -345,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[ @@ -368,6 +570,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( binding_type=binding_type, @@ -399,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( @@ -408,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[ @@ -437,8 +701,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserBindingPage(self._version, response, self._solution) + 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 UserBindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -469,10 +739,94 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserBindingPage(self._version, response, self._solution) + 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: """ @@ -484,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: """ @@ -496,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 51239956f0..db12f64be8 100644 --- a/twilio/rest/ip_messaging/v2/service/user/user_channel.py +++ b/twilio/rest/ip_messaging/v2/service/user/user_channel.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class UserChannelInstance(InstanceResource): + class ChannelStatus(object): JOINED = "joined" INVITED = "invited" @@ -73,15 +74,16 @@ def __init__( ) self.links: Optional[Dict[str, object]] = payload.get("links") self.url: Optional[str] = payload.get("url") - self.notification_level: Optional[ - "UserChannelInstance.NotificationLevel" - ] = payload.get("notification_level") + self.notification_level: Optional["UserChannelInstance.NotificationLevel"] = ( + payload.get("notification_level") + ) self._solution = { "service_sid": service_sid, "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 @@ -194,6 +278,7 @@ def __repr__(self) -> str: class UserChannelContext(InstanceContext): + def __init__( self, version: Version, service_sid: str, user_sid: str, channel_sid: str ): @@ -219,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 @@ -226,9 +325,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -238,9 +359,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the UserChannelInstance 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) -> UserChannelInstance: @@ -250,19 +395,47 @@ def fetch(self) -> UserChannelInstance: :returns: The fetched UserChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], ) - return UserChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> UserChannelInstance: """ @@ -271,37 +444,47 @@ async def fetch_async(self) -> UserChannelInstance: :returns: The fetched UserChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return UserChannelInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + user_sid=self._solution["user_sid"], + channel_sid=self._solution["channel_sid"], ) - return UserChannelInstance( + 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( + 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( { "NotificationLevel": notification_level, @@ -311,13 +494,38 @@ def update( ), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -326,23 +534,52 @@ 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( { "NotificationLevel": notification_level, @@ -352,13 +589,38 @@ async def update_async( ), } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -367,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 @@ -378,12 +671,14 @@ def __repr__(self) -> str: class UserChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UserChannelInstance: """ Build an instance of UserChannelInstance :param payload: Payload response from the API """ + return UserChannelInstance( self._version, payload, @@ -401,6 +696,7 @@ def __repr__(self) -> str: class UserChannelList(ListResource): + def __init__(self, version: Version, service_sid: str, user_sid: str): """ Initialize the UserChannelList @@ -471,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, @@ -490,6 +836,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -516,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( @@ -524,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, @@ -548,8 +946,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UserChannelPage(self._version, response, self._solution) + 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 UserChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -575,10 +979,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UserChannelPage(self._version, response, self._solution) + 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: """ @@ -590,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: """ @@ -602,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/knowledge/KnowledgeBase.py b/twilio/rest/knowledge/KnowledgeBase.py new file mode 100644 index 0000000000..c92fd50540 --- /dev/null +++ b/twilio/rest/knowledge/KnowledgeBase.py @@ -0,0 +1,55 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + 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.domain import Domain +from twilio.rest import Client +from twilio.rest.knowledge.v1 import V1 +from twilio.rest.knowledge.v2 import V2 + + +class KnowledgeBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Knowledge Domain + + :returns: Domain for Knowledge + """ + 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 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 "" 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 fad9f85c49..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,28 +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/knowledge/v1/knowledge/__init__.py b/twilio/rest/knowledge/v1/knowledge/__init__.py new file mode 100644 index 0000000000..55395f0737 --- /dev/null +++ b/twilio/rest/knowledge/v1/knowledge/__init__.py @@ -0,0 +1,1432 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Knowledge + 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 +from twilio.rest.knowledge.v1.knowledge.chunk import ChunkList +from twilio.rest.knowledge.v1.knowledge.knowledge_status import KnowledgeStatusList + + +class KnowledgeInstance(InstanceResource): + + class KnowledgeV1ServiceCreateKnowledgeRequest(object): + """ + :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. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + def __init__(self, payload: Dict[str, Any]): + + 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.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 { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + class KnowledgeV1ServiceCreatePolicyRequest(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 KnowledgeV1ServiceUpdateKnowledgeRequest(object): + """ + :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 knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + 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.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 { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + """ + :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], 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 = { + "id": id or self.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, + id=self._solution["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, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> "KnowledgeInstance": + """ + Update the KnowledgeInstance + + :param knowledge_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + return self._proxy.update( + knowledge_v1_service_update_knowledge_request=knowledge_v1_service_update_knowledge_request, + ) + + 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 + """ + return await self._proxy.update_async( + 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 + def chunks(self) -> ChunkList: + """ + Access the chunks + """ + return self._proxy.chunks + + @property + def knowledge_status(self) -> KnowledgeStatusList: + """ + Access the knowledge_status + """ + return self._proxy.knowledge_status + + 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 KnowledgeContext(InstanceContext): + + class KnowledgeV1ServiceCreateKnowledgeRequest(object): + """ + :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. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + def __init__(self, payload: Dict[str, Any]): + + 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.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 { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + class KnowledgeV1ServiceCreatePolicyRequest(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 KnowledgeV1ServiceUpdateKnowledgeRequest(object): + """ + :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 knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + 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.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 { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeContext + + :param version: Version that contains the resource + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}".format(**self._solution) + + 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 + + + :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 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, + id=self._solution["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, + 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) -> 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"], + ) + + 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, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = knowledge_v1_service_update_knowledge_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, + knowledge_v1_service_update_knowledge_request: Union[ + KnowledgeV1ServiceUpdateKnowledgeRequest, object + ] = values.unset, + ) -> KnowledgeInstance: + """ + Update the KnowledgeInstance + + :param knowledge_v1_service_update_knowledge_request: + + :returns: The updated KnowledgeInstance + """ + 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({}) + + 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, + 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: + """ + Access the chunks + """ + if self._chunks is None: + self._chunks = ChunkList( + self._version, + self._solution["id"], + ) + return self._chunks + + @property + def knowledge_status(self) -> KnowledgeStatusList: + """ + Access the knowledge_status + """ + if self._knowledge_status is None: + self._knowledge_status = KnowledgeStatusList( + self._version, + self._solution["id"], + ) + return self._knowledge_status + + 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 KnowledgePage(Page): + + 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) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class KnowledgeList(ListResource): + + class KnowledgeV1ServiceCreateKnowledgeRequest(object): + """ + :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. + :ivar policy: + :ivar type: The type of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's required for 'Database' type but disallowed for other types. + """ + + def __init__(self, payload: Dict[str, Any]): + + 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.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 { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + class KnowledgeV1ServiceCreatePolicyRequest(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 KnowledgeV1ServiceUpdateKnowledgeRequest(object): + """ + :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 knowledge source. + :ivar policy: + :ivar type: The description of the knowledge source. + :ivar embedding_model: The embedding model to be used for the knowledge source. It's only applicable to 'Database' type. + """ + + def __init__(self, payload: Dict[str, Any]): + + 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.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 { + "description": self.description, + "knowledge_source_details": self.knowledge_source_details, + "name": self.name, + "policy": self.policy.to_dict() if self.policy is not None else None, + "type": self.type, + "embedding_model": self.embedding_model, + } + + def __init__(self, version: Version): + """ + Initialize the KnowledgeList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Knowledge" + + def _create( + self, + knowledge_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> tuple: + """ + Internal 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"}) + + 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_v1_service_create_knowledge_request: KnowledgeV1ServiceCreateKnowledgeRequest, + ) -> KnowledgeInstance: + """ + Create the KnowledgeInstance + + :param knowledge_v1_service_create_knowledge_request: + + :returns: The created KnowledgeInstance + """ + 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"}) + + 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_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, + tags: 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(tags=tags, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + tags: 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, 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, + tags: 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 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: list that will contain up to limit results + """ + + return list( + self.stream( + tags=tags, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + tags: 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 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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + 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, + 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, + ) -> KnowledgePage: + """ + Retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :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: Page of KnowledgeInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return KnowledgePage(self._version, response) + + async def page_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, + ) -> KnowledgePage: + """ + Asynchronously retrieve a single page of KnowledgeInstance records from the API. + Request is executed immediately + + :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: Page of KnowledgeInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + 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) + + 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) + + def get(self, id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param id: + """ + return KnowledgeContext(self._version, id=id) + + def __call__(self, id: str) -> KnowledgeContext: + """ + Constructs a KnowledgeContext + + :param id: + """ + return KnowledgeContext(self._version, id=id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v1/knowledge/chunk.py b/twilio/rest/knowledge/v1/knowledge/chunk.py new file mode 100644 index 0000000000..97dbe422d6 --- /dev/null +++ b/twilio/rest/knowledge/v1/knowledge/chunk.py @@ -0,0 +1,471 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Knowledge + 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_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class ChunkInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar content: The chunk content. + :ivar metadata: The metadata of the chunk. + :ivar date_created: The date and time in GMT when the Chunk 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 Chunk was 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.account_sid: Optional[str] = payload.get("account_sid") + self.content: Optional[str] = payload.get("content") + self.metadata: Optional[Dict[str, object]] = payload.get("metadata") + 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 ChunkPage(Page): + + 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, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChunkList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the ChunkList + + :param version: Version that contains the resource + :param id: The knowledge ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}/Chunks".format(**self._solution) + + def stream( + self, + 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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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[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 limit: Upper limit for the number of records to return. stream() + guarantees to never return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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 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, + 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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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[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 limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + 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 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, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChunkPage: + """ + Retrieve a single page of ChunkInstance 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 ChunkInstance + """ + data = values.of( + { + "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 ChunkPage(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, + ) -> ChunkPage: + """ + Asynchronously retrieve a single page of ChunkInstance 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 ChunkInstance + """ + data = values.of( + { + "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 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: + """ + 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 "" diff --git a/twilio/rest/knowledge/v1/knowledge/knowledge_status.py b/twilio/rest/knowledge/v1/knowledge/knowledge_status.py new file mode 100644 index 0000000000..950318b3ac --- /dev/null +++ b/twilio/rest/knowledge/v1/knowledge/knowledge_status.py @@ -0,0 +1,264 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Knowledge + 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 KnowledgeStatusInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Knowledge resource. + :ivar status: The status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :ivar last_status: The last status of processing the knowledge source ('QUEUED', 'PROCESSING', 'COMPLETED', 'FAILED') + :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], id: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.status: Optional[str] = payload.get("status") + self.last_status: Optional[str] = payload.get("last_status") + self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_updated") + ) + + self._solution = { + "id": id, + } + + self._context: Optional[KnowledgeStatusContext] = None + + @property + def _proxy(self) -> "KnowledgeStatusContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: KnowledgeStatusContext for this KnowledgeStatusInstance + """ + if self._context is None: + self._context = KnowledgeStatusContext( + self._version, + id=self._solution["id"], + ) + return self._context + + def fetch(self) -> "KnowledgeStatusInstance": + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "KnowledgeStatusInstance": + """ + Asynchronous coroutine to fetch the KnowledgeStatusInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KnowledgeStatusContext(InstanceContext): + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeStatusContext + + :param version: Version that contains the resource + :param id: the Knowledge ID. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + self._uri = "/Knowledge/{id}/Status".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) -> KnowledgeStatusInstance: + """ + Fetch the KnowledgeStatusInstance + + + :returns: The fetched KnowledgeStatusInstance + """ + payload, _, _ = self._fetch() + return KnowledgeStatusInstance( + self._version, + payload, + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the KnowledgeStatusInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class KnowledgeStatusList(ListResource): + + def __init__(self, version: Version, id: str): + """ + Initialize the KnowledgeStatusList + + :param version: Version that contains the resource + :param id: the Knowledge ID. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "id": id, + } + + def get(self) -> KnowledgeStatusContext: + """ + Constructs a KnowledgeStatusContext + + """ + return KnowledgeStatusContext(self._version, id=self._solution["id"]) + + def __call__(self) -> KnowledgeStatusContext: + """ + Constructs a KnowledgeStatusContext + + """ + return KnowledgeStatusContext(self._version, id=self._solution["id"]) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/knowledge/v2/__init__.py b/twilio/rest/knowledge/v2/__init__.py new file mode 100644 index 0000000000..f329d0911d --- /dev/null +++ b/twilio/rest/knowledge/v2/__init__.py @@ -0,0 +1,96 @@ +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) + return list_instance(kb_id) + + 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..6537de31a8 --- /dev/null +++ b/twilio/rest/knowledge/v2/chunk.py @@ -0,0 +1,505 @@ +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. + """ + + 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") + ) + + # 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 "".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 "" + + +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 "" diff --git a/twilio/rest/knowledge/v2/knowledge.py b/twilio/rest/knowledge/v2/knowledge.py new file mode 100644 index 0000000000..446135b3cc --- /dev/null +++ b/twilio/rest/knowledge/v2/knowledge.py @@ -0,0 +1,1249 @@ +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" + TEXT_MDX = "text/mdx" + 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 "".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 "".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 "" + + +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) or the permanent S3 location after upload completes. 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 "" diff --git a/twilio/rest/knowledge/v2/knowledge_basis.py b/twilio/rest/knowledge/v2/knowledge_basis.py new file mode 100644 index 0000000000..629b2083b9 --- /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 message: + :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 status_url: URI to check operation status. + """ + + def __init__( + self, version: Version, payload: ResponseResource, kb_id: Optional[str] = None + ): + super().__init__(version) + + self.message: Optional[str] = payload.get("message") + 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.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 "".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 "".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 "" + + +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 "" 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 "".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 "".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 "" diff --git a/twilio/rest/knowledge/v2/search.py b/twilio/rest/knowledge/v2/search.py new file mode 100644 index 0000000000..cf2f5ff87c --- /dev/null +++ b/twilio/rest/knowledge/v2/search.py @@ -0,0 +1,305 @@ +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_context import InstanceContext +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: Optional[str] = None + ): + 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, + } + + self._context: Optional[SearchContext] = None + + @property + def _proxy(self) -> "SearchContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: SearchContext for this SearchInstance + """ + if self._context is None: + self._context = SearchContext( + self._version, + kb_id=self._solution["kb_id"], + ) + return self._context + + def create( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> "SearchInstance": + """ + Create the SearchInstance + + :param knowledge_search: + + :returns: The created SearchInstance + """ + return self._proxy.create( + knowledge_search=knowledge_search, + ) + + async def create_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> "SearchInstance": + """ + Asynchronous coroutine to create the SearchInstance + + :param knowledge_search: + + :returns: The created SearchInstance + """ + return await self._proxy.create_async( + knowledge_search=knowledge_search, + ) + + def create_with_http_info( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> ApiResponse: + """ + Create the SearchInstance with HTTP info + + :param knowledge_search: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.create_with_http_info( + knowledge_search=knowledge_search, + ) + + async def create_with_http_info_async( + self, knowledge_search: Union[KnowledgeSearch, object] = values.unset + ) -> ApiResponse: + """ + Asynchronous coroutine to create the SearchInstance with HTTP info + + :param knowledge_search: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.create_with_http_info_async( + knowledge_search=knowledge_search, + ) + + 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 SearchContext(InstanceContext): + + def __init__(self, version: Version, kb_id: str): + """ + Initialize the SearchContext + + :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({}) + + 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({}) + + 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: + """ + Asynchronous coroutine to 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: + """ + Asynchronous coroutine to 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 + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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): + """ + Initialize the SearchList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, kb_id: str) -> SearchContext: + """ + Constructs a SearchContext + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + return SearchContext(self._version, kb_id=kb_id) + + def __call__(self, kb_id: str) -> SearchContext: + """ + Constructs a SearchContext + + :param kb_id: A unique Knowledge Base ID using Twilio Type ID (TTID) format + """ + return SearchContext(self._version, kb_id=kb_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/lookups/LookupsBase.py b/twilio/rest/lookups/LookupsBase.py index fe3aa2aa6d..e24f8dc611 100644 --- a/twilio/rest/lookups/LookupsBase.py +++ b/twilio/rest/lookups/LookupsBase.py @@ -18,6 +18,7 @@ class LookupsBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Lookups Domain diff --git a/twilio/rest/lookups/v1/__init__.py b/twilio/rest/lookups/v1/__init__.py index 82f17cc04f..72204da366 100644 --- a/twilio/rest/lookups/v1/__init__.py +++ b/twilio/rest/lookups/v1/__init__.py @@ -19,6 +19,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Lookups diff --git a/twilio/rest/lookups/v1/phone_number.py b/twilio/rest/lookups/v1/phone_number.py index f38a5c9f0b..66ac1d0d6e 100644 --- a/twilio/rest/lookups/v1/phone_number.py +++ b/twilio/rest/lookups/v1/phone_number.py @@ -12,9 +12,9 @@ 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 @@ -22,7 +22,6 @@ class PhoneNumberInstance(InstanceResource): - """ :ivar caller_name: The name of the phone number's owner. If `null`, that information was not available. :ivar country_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) for the phone number. @@ -52,6 +51,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PhoneNumberContext] = None @property @@ -80,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. @@ -104,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. @@ -117,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 @@ -128,6 +176,7 @@ def __repr__(self) -> str: class PhoneNumberContext(InstanceContext): + def __init__(self, version: Version, phone_number: str): """ Initialize the PhoneNumberContext @@ -143,78 +192,188 @@ 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 - - :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. + Internal helper for fetch operation - :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), "AddOns": serialize.map(add_ons, lambda e: e), } ) - data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + params.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) + + 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, + 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) + + 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 - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "CountryCode": country_code, "Type": serialize.map(type, lambda e: e), "AddOns": serialize.map(add_ons, lambda e: e), } ) - data.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + params.update(serialize.prefixed_collapsible_map(add_ons_data, "AddOns")) + + 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, + 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 @@ -226,6 +385,7 @@ def __repr__(self) -> str: class PhoneNumberList(ListResource): + def __init__(self, version: Version): """ Initialize the PhoneNumberList diff --git a/twilio/rest/lookups/v2/__init__.py b/twilio/rest/lookups/v2/__init__.py index 1cea8ab0b2..852f552540 100644 --- a/twilio/rest/lookups/v2/__init__.py +++ b/twilio/rest/lookups/v2/__init__.py @@ -15,10 +15,15 @@ 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): + def __init__(self, domain: Domain): """ Initialize the V2 version of Lookups @@ -26,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: @@ -34,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 "".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 "".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 "" 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 "".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 "".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 "" diff --git a/twilio/rest/lookups/v2/phone_number.py b/twilio/rest/lookups/v2/phone_number.py index 676a3fdfb7..2240351721 100644 --- a/twilio/rest/lookups/v2/phone_number.py +++ b/twilio/rest/lookups/v2/phone_number.py @@ -12,9 +12,9 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,6 +22,7 @@ class PhoneNumberInstance(InstanceResource): + class ValidationError(object): TOO_SHORT = "TOO_SHORT" TOO_LONG = "TOO_LONG" @@ -37,13 +38,16 @@ 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 live_activity: An object that contains live activity 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 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. """ @@ -60,27 +64,29 @@ 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.live_activity: Optional[Dict[str, object]] = payload.get("live_activity") - 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.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" ) + self.pre_fill: Optional[Dict[str, object]] = payload.get("pre_fill") self.url: Optional[str] = payload.get("url") self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PhoneNumberContext] = None @property @@ -112,11 +118,14 @@ def fetch( 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 caller_name, sim_swap, call_forwarding, live_activity, line_type_intelligence, identity_match. + :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. @@ -128,6 +137,9 @@ def fetch( :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 """ @@ -144,6 +156,9 @@ def fetch( 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_async( @@ -160,11 +175,14 @@ async def fetch_async( 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 caller_name, sim_swap, call_forwarding, live_activity, line_type_intelligence, identity_match. + :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. @@ -176,6 +194,9 @@ async def fetch_async( :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 """ @@ -192,6 +213,123 @@ async def fetch_async( 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 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: @@ -205,6 +343,7 @@ def __repr__(self) -> str: class PhoneNumberContext(InstanceContext): + def __init__(self, version: Version, phone_number: str): """ Initialize the PhoneNumberContext @@ -220,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, @@ -234,27 +373,18 @@ def fetch( address_country_code: Union[str, object] = values.unset, national_id: Union[str, object] = values.unset, date_of_birth: Union[str, object] = values.unset, - ) -> PhoneNumberInstance: + last_verified_date: Union[str, object] = values.unset, + verification_sid: Union[str, object] = values.unset, + 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 caller_name, sim_swap, call_forwarding, live_activity, line_type_intelligence, identity_match. - :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. + 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, @@ -268,18 +398,83 @@ def fetch( "AddressCountryCode": address_country_code, "NationalId": national_id, "DateOfBirth": date_of_birth, + "LastVerifiedDate": last_verified_date, + "VerificationSid": verification_sid, + "PartnerSubId": partner_sub_id, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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, @@ -293,11 +488,14 @@ async def fetch_async( address_country_code: Union[str, object] = values.unset, national_id: Union[str, object] = values.unset, date_of_birth: Union[str, object] = values.unset, - ) -> PhoneNumberInstance: + 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 + Fetch the PhoneNumberInstance and return response metadata - :param fields: A comma-separated list of fields to return. Possible values are caller_name, sim_swap, call_forwarding, live_activity, line_type_intelligence, identity_match. + :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. @@ -309,11 +507,62 @@ async def fetch_async( :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 + :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) - data = values.of( + 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 + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Fields": fields, "CountryCode": country_code, @@ -327,19 +576,145 @@ async def fetch_async( "AddressCountryCode": address_country_code, "NationalId": national_id, "DateOfBirth": date_of_birth, + "LastVerifiedDate": last_verified_date, + "VerificationSid": verification_sid, + "PartnerSubId": partner_sub_id, } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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 @@ -351,6 +726,7 @@ def __repr__(self) -> str: class PhoneNumberList(ListResource): + def __init__(self, version: Version): """ Initialize the PhoneNumberList 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 "" + + +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 "" 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 "" + + +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 "" diff --git a/twilio/rest/marketplace/MarketplaceBase.py b/twilio/rest/marketplace/MarketplaceBase.py new file mode 100644 index 0000000000..9fbe193d99 --- /dev/null +++ b/twilio/rest/marketplace/MarketplaceBase.py @@ -0,0 +1,44 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + 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.domain import Domain +from twilio.rest import Client +from twilio.rest.marketplace.v1 import V1 + + +class MarketplaceBase(Domain): + + def __init__(self, twilio: Client): + """ + Initialize the Marketplace Domain + + :returns: Domain for Marketplace + """ + super().__init__(twilio, "https://marketplace.twilio.com") + self._v1: Optional[V1] = None + + @property + def v1(self) -> V1: + """ + :returns: Versions v1 of Marketplace + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/marketplace/__init__.py b/twilio/rest/marketplace/__init__.py new file mode 100644 index 0000000000..f0276a8f84 --- /dev/null +++ b/twilio/rest/marketplace/__init__.py @@ -0,0 +1,9 @@ +from twilio.rest.marketplace.MarketplaceBase import MarketplaceBase + + +class Marketplace(MarketplaceBase): + def available_add_ons(self): + return self.v1.available_add_ons + + def installed_add_ons(self): + return self.v1.installed_add_ons diff --git a/twilio/rest/marketplace/v1/__init__.py b/twilio/rest/marketplace/v1/__init__.py new file mode 100644 index 0000000000..6a84b31cd9 --- /dev/null +++ b/twilio/rest/marketplace/v1/__init__.py @@ -0,0 +1,75 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + 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.marketplace.v1.available_add_on import AvailableAddOnList +from twilio.rest.marketplace.v1.installed_add_on import InstalledAddOnList +from twilio.rest.marketplace.v1.module_data import ModuleDataList +from twilio.rest.marketplace.v1.module_data_management import ModuleDataManagementList +from twilio.rest.marketplace.v1.referral_conversion import ReferralConversionList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Marketplace + + :param domain: The Twilio.marketplace domain + """ + super().__init__(domain, "v1") + self._available_add_ons: Optional[AvailableAddOnList] = None + self._installed_add_ons: Optional[InstalledAddOnList] = None + self._module_data: Optional[ModuleDataList] = None + self._module_data_management: Optional[ModuleDataManagementList] = None + self._referral_conversion: Optional[ReferralConversionList] = None + + @property + def available_add_ons(self) -> AvailableAddOnList: + if self._available_add_ons is None: + self._available_add_ons = AvailableAddOnList(self) + return self._available_add_ons + + @property + def installed_add_ons(self) -> InstalledAddOnList: + if self._installed_add_ons is None: + self._installed_add_ons = InstalledAddOnList(self) + return self._installed_add_ons + + @property + def module_data(self) -> ModuleDataList: + if self._module_data is None: + self._module_data = ModuleDataList(self) + return self._module_data + + @property + def module_data_management(self) -> ModuleDataManagementList: + if self._module_data_management is None: + self._module_data_management = ModuleDataManagementList(self) + return self._module_data_management + + @property + def referral_conversion(self) -> ReferralConversionList: + if self._referral_conversion is None: + self._referral_conversion = ReferralConversionList(self) + return self._referral_conversion + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/marketplace/v1/available_add_on/__init__.py b/twilio/rest/marketplace/v1/available_add_on/__init__.py new file mode 100644 index 0000000000..53ed2aeb1d --- /dev/null +++ b/twilio/rest/marketplace/v1/available_add_on/__init__.py @@ -0,0 +1,679 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + 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 +from twilio.rest.marketplace.v1.available_add_on.available_add_on_extension import ( + AvailableAddOnExtensionList, +) + + +class AvailableAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar pricing_type: How customers are charged for using this Add-on. + :ivar configuration_schema: The JSON object with the configuration that must be provided when installing a given Add-on. + :ivar url: The absolute URL of the resource. + :ivar links: The 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.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.pricing_type: Optional[str] = payload.get("pricing_type") + self.configuration_schema: Optional[Dict[str, object]] = payload.get( + "configuration_schema" + ) + 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[AvailableAddOnContext] = None + + @property + def _proxy(self) -> "AvailableAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnContext for this AvailableAddOnInstance + """ + if self._context is None: + self._context = AvailableAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnInstance": + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnInstance + + + :returns: The fetched 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: + """ + Access the extensions + """ + return self._proxy.extensions + + 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 AvailableAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AvailableAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/AvailableAddOns/{sid}".format(**self._solution) + + self._extensions: Optional[AvailableAddOnExtensionList] = None + + 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) -> AvailableAddOnInstance: + """ + Fetch the AvailableAddOnInstance + + + :returns: The fetched AvailableAddOnInstance + """ + payload, _, _ = self._fetch() + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance and return response metadata + + + :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" + + 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: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = AvailableAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + 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 AvailableAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: + """ + Build an instance of AvailableAddOnInstance + + :param payload: Payload response from the API + """ + + return AvailableAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AvailableAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AvailableAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/AvailableAddOns" + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnInstance]: + """ + Streams AvailableAddOnInstance 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[AvailableAddOnInstance]: + """ + Asynchronously streams AvailableAddOnInstance 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 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, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnInstance]: + """ + Lists AvailableAddOnInstance 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[AvailableAddOnInstance]: + """ + Asynchronously lists AvailableAddOnInstance 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 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, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnPage: + """ + Retrieve a single page of AvailableAddOnInstance 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 AvailableAddOnInstance + """ + data = values.of( + { + "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 AvailableAddOnPage(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, + ) -> AvailableAddOnPage: + """ + Asynchronously retrieve a single page of AvailableAddOnInstance 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 AvailableAddOnInstance + """ + data = values.of( + { + "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 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AvailableAddOnPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnPage(self._version, response) + + def get(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AvailableAddOnContext: + """ + Constructs a AvailableAddOnContext + + :param sid: The SID of the AvailableAddOn resource to fetch. + """ + return AvailableAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" 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 new file mode 100644 index 0000000000..14dcfed3af --- /dev/null +++ b/twilio/rest/marketplace/v1/available_add_on/available_add_on_extension.py @@ -0,0 +1,700 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + 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 AvailableAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the AvailableAddOnExtension resource. + :ivar available_add_on_sid: The SID of the AvailableAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + available_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.available_add_on_sid: Optional[str] = payload.get("available_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid or self.sid, + } + + self._context: Optional[AvailableAddOnExtensionContext] = None + + @property + def _proxy(self) -> "AvailableAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AvailableAddOnExtensionContext for this AvailableAddOnExtensionInstance + """ + if self._context is None: + self._context = AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "AvailableAddOnExtensionInstance": + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AvailableAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AvailableAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, available_add_on_sid: str, sid: str): + """ + Initialize the AvailableAddOnExtensionContext + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extension to fetch. + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + "sid": sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions/{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) -> AvailableAddOnExtensionInstance: + """ + Fetch the AvailableAddOnExtensionInstance + + + :returns: The fetched AvailableAddOnExtensionInstance + """ + payload, _, _ = self._fetch() + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnExtensionInstance and return response metadata + + + :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" + + 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, + available_add_on_sid=self._solution["available_add_on_sid"], + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class AvailableAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstance: + """ + Build an instance of AvailableAddOnExtensionInstance + + :param payload: Payload response from the API + """ + + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AvailableAddOnExtensionList(ListResource): + + def __init__(self, version: Version, available_add_on_sid: str): + """ + Initialize the AvailableAddOnExtensionList + + :param version: Version that contains the resource + :param available_add_on_sid: The SID of the AvailableAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "available_add_on_sid": available_add_on_sid, + } + self._uri = "/AvailableAddOns/{available_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AvailableAddOnExtensionInstance]: + """ + Streams AvailableAddOnExtensionInstance 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[AvailableAddOnExtensionInstance]: + """ + Asynchronously streams AvailableAddOnExtensionInstance 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 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, + page_size: Optional[int] = None, + ) -> List[AvailableAddOnExtensionInstance]: + """ + Lists AvailableAddOnExtensionInstance 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[AvailableAddOnExtensionInstance]: + """ + Asynchronously lists AvailableAddOnExtensionInstance 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 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, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AvailableAddOnExtensionPage: + """ + Retrieve a single page of AvailableAddOnExtensionInstance 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 AvailableAddOnExtensionInstance + """ + data = values.of( + { + "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 AvailableAddOnExtensionPage( + 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, + ) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a single page of AvailableAddOnExtensionInstance 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 AvailableAddOnExtensionInstance + """ + data = values.of( + { + "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 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: + """ + Retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + async def get_page_async(self, target_url: str) -> AvailableAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of AvailableAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AvailableAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def get(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> AvailableAddOnExtensionContext: + """ + Constructs a AvailableAddOnExtensionContext + + :param sid: The SID of the AvailableAddOn Extension resource to fetch. + """ + return AvailableAddOnExtensionContext( + self._version, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/marketplace/v1/installed_add_on/__init__.py b/twilio/rest/marketplace/v1/installed_add_on/__init__.py new file mode 100644 index 0000000000..2553e78bf8 --- /dev/null +++ b/twilio/rest/marketplace/v1/installed_add_on/__init__.py @@ -0,0 +1,1191 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + 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 +from twilio.rest.marketplace.v1.installed_add_on.installed_add_on_extension import ( + InstalledAddOnExtensionList, +) +from twilio.rest.marketplace.v1.installed_add_on.installed_add_on_usage import ( + InstalledAddOnUsageList, +) + + +class InstalledAddOnInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn resource. This Sid can also be found in the Console on that specific Add-ons page as the 'Available Add-on Sid'. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the InstalledAddOn resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar description: A short description of the Add-on's functionality. + :ivar configuration: The JSON object that represents the current configuration of installed Add-on. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :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. + :ivar links: The 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.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.description: Optional[str] = payload.get("description") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + 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[InstalledAddOnContext] = None + + @property + def _proxy(self) -> "InstalledAddOnContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnContext for this InstalledAddOnInstance + """ + if self._context is None: + self._context = InstalledAddOnContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched InstalledAddOnInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnInstance + + + :returns: The fetched 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, + unique_name: Union[str, object] = values.unset, + ) -> "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 + """ + return self._proxy.update( + configuration=configuration, + unique_name=unique_name, + ) + + 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 + """ + return await self._proxy.update_async( + configuration=configuration, + 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: + """ + Access the extensions + """ + return self._proxy.extensions + + @property + def usage(self) -> InstalledAddOnUsageList: + """ + Access the usage + """ + return self._proxy.usage + + 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 InstalledAddOnContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the InstalledAddOnContext + + :param version: Version that contains the resource + :param sid: The SID of the InstalledAddOn resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/InstalledAddOns/{sid}".format(**self._solution) + + 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 + + + :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 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 InstalledAddOnInstance + + + :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 InstalledAddOnInstance 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) -> InstalledAddOnInstance: + """ + Fetch the InstalledAddOnInstance + + + :returns: The fetched InstalledAddOnInstance + """ + payload, _, _ = self._fetch() + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnInstance and return response metadata + + + :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" + + 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"], + ) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_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, + configuration: Union[object, object] = values.unset, + unique_name: Union[str, object] = values.unset, + ) -> 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( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_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, + 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: + """ + Access the extensions + """ + if self._extensions is None: + self._extensions = InstalledAddOnExtensionList( + self._version, + self._solution["sid"], + ) + return self._extensions + + @property + def usage(self) -> InstalledAddOnUsageList: + """ + Access the usage + """ + if self._usage is None: + self._usage = InstalledAddOnUsageList( + self._version, + self._solution["sid"], + ) + return self._usage + + 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 InstalledAddOnPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: + """ + Build an instance of InstalledAddOnInstance + + :param payload: Payload response from the API + """ + + return InstalledAddOnInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InstalledAddOnList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the InstalledAddOnList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/InstalledAddOns" + + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + 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: + """ + 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, _, _ = 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( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "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" + + 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, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnInstance]: + """ + Streams InstalledAddOnInstance 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[InstalledAddOnInstance]: + """ + Asynchronously streams InstalledAddOnInstance 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 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, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnInstance]: + """ + Lists InstalledAddOnInstance 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[InstalledAddOnInstance]: + """ + Asynchronously lists InstalledAddOnInstance 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 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, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnPage: + """ + Retrieve a single page of InstalledAddOnInstance 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 InstalledAddOnInstance + """ + data = values.of( + { + "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 InstalledAddOnPage(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, + ) -> InstalledAddOnPage: + """ + Asynchronously retrieve a single page of InstalledAddOnInstance 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 InstalledAddOnInstance + """ + data = values.of( + { + "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 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnPage(self._version, response) + + async def get_page_async(self, target_url: str) -> InstalledAddOnPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnPage(self._version, response) + + def get(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __call__(self, sid: str) -> InstalledAddOnContext: + """ + Constructs a InstalledAddOnContext + + :param sid: The SID of the InstalledAddOn resource to update. + """ + return InstalledAddOnContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" 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 new file mode 100644 index 0000000000..844c78e33f --- /dev/null +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_extension.py @@ -0,0 +1,862 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + 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.api_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 InstalledAddOnExtensionInstance(InstanceResource): + """ + :ivar sid: The unique string that we created to identify the InstalledAddOn Extension resource. + :ivar installed_add_on_sid: The SID of the InstalledAddOn resource to which this extension applies. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar product_name: The name of the Product this Extension is used within. + :ivar unique_name: An application-defined string that uniquely identifies the resource. + :ivar enabled: Whether the Extension will be invoked. + :ivar url: The absolute URL of the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + installed_add_on_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.installed_add_on_sid: Optional[str] = payload.get("installed_add_on_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product_name: Optional[str] = payload.get("product_name") + self.unique_name: Optional[str] = payload.get("unique_name") + self.enabled: Optional[bool] = payload.get("enabled") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid or self.sid, + } + + self._context: Optional[InstalledAddOnExtensionContext] = None + + @property + def _proxy(self) -> "InstalledAddOnExtensionContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: InstalledAddOnExtensionContext for this InstalledAddOnExtensionInstance + """ + if self._context is None: + self._context = InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "InstalledAddOnExtensionInstance": + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "InstalledAddOnExtensionInstance": + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched 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 + + :param enabled: Whether the Extension should be invoked. + + :returns: The updated InstalledAddOnExtensionInstance + """ + return self._proxy.update( + enabled=enabled, + ) + + 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 + """ + return await self._proxy.update_async( + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InstalledAddOnExtensionContext(InstanceContext): + + def __init__(self, version: Version, installed_add_on_sid: str, sid: str): + """ + Initialize the InstalledAddOnExtensionContext + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extension to update. + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + "sid": sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions/{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) -> InstalledAddOnExtensionInstance: + """ + Fetch the InstalledAddOnExtensionInstance + + + :returns: The fetched InstalledAddOnExtensionInstance + """ + payload, _, _ = self._fetch() + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnExtensionInstance and return response metadata + + + :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" + + 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, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the InstalledAddOnExtensionInstance and return response metadata + + + :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( + { + "Enabled": serialize.boolean_to_string(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, 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, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], + ) + + def update_with_http_info(self, enabled: bool) -> ApiResponse: + """ + 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 = 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( + { + "Enabled": serialize.boolean_to_string(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, 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, + installed_add_on_sid=self._solution["installed_add_on_sid"], + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class InstalledAddOnExtensionPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstance: + """ + Build an instance of InstalledAddOnExtensionInstance + + :param payload: Payload response from the API + """ + + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class InstalledAddOnExtensionList(ListResource): + + def __init__(self, version: Version, installed_add_on_sid: str): + """ + Initialize the InstalledAddOnExtensionList + + :param version: Version that contains the resource + :param installed_add_on_sid: The SID of the InstalledAddOn resource with the extensions to read. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Extensions".format( + **self._solution + ) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[InstalledAddOnExtensionInstance]: + """ + Streams InstalledAddOnExtensionInstance 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[InstalledAddOnExtensionInstance]: + """ + Asynchronously streams InstalledAddOnExtensionInstance 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 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, + page_size: Optional[int] = None, + ) -> List[InstalledAddOnExtensionInstance]: + """ + Lists InstalledAddOnExtensionInstance 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[InstalledAddOnExtensionInstance]: + """ + Asynchronously lists InstalledAddOnExtensionInstance 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 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, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> InstalledAddOnExtensionPage: + """ + Retrieve a single page of InstalledAddOnExtensionInstance 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 InstalledAddOnExtensionInstance + """ + data = values.of( + { + "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 InstalledAddOnExtensionPage( + 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, + ) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a single page of InstalledAddOnExtensionInstance 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 InstalledAddOnExtensionInstance + """ + data = values.of( + { + "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 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: + """ + Retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + async def get_page_async(self, target_url: str) -> InstalledAddOnExtensionPage: + """ + Asynchronously retrieve a specific page of InstalledAddOnExtensionInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of InstalledAddOnExtensionInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) + + def get(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> InstalledAddOnExtensionContext: + """ + Constructs a InstalledAddOnExtensionContext + + :param sid: The SID of the InstalledAddOn Extension resource to update. + """ + return InstalledAddOnExtensionContext( + self._version, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" 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 new file mode 100644 index 0000000000..9a2a66844b --- /dev/null +++ b/twilio/rest/marketplace/v1/installed_add_on/installed_add_on_usage.py @@ -0,0 +1,303 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + 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 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 InstalledAddOnUsageInstance(InstanceResource): + + class MarketplaceV1InstalledAddOnInstalledAddOnUsage(object): + """ + :ivar total_submitted: Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + :ivar billable_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) + self.billable_items: Optional[ + List[ + InstalledAddOnUsageList.MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems + ] + ] = payload.get("billable_items") + + def to_dict(self): + return { + "total_submitted": self.total_submitted, + "billable_items": ( + [billable_items.to_dict() for billable_items in self.billable_items] + if self.billable_items is not None + else None + ), + } + + class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems(object): + """ + :ivar quantity: Total amount in local currency that was billed for this Billing Item. Can be any floating number greater than 0. + :ivar sid: BillingSid to use for billing. + :ivar submitted: Whether the billing event was successfully generated for this Billable Item. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.quantity: Optional[float] = payload.get("quantity") + self.sid: Optional[str] = payload.get("sid") + self.submitted: Optional[bool] = payload.get("submitted") + + def to_dict(self): + return { + "quantity": self.quantity, + "sid": self.sid, + "submitted": self.submitted, + } + + """ + :ivar total_submitted: Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + :ivar billable_items: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], installed_add_on_sid: str + ): + super().__init__(version) + + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) + self.billable_items: Optional[List[InstalledAddOnUsageList.str]] = payload.get( + "billable_items" + ) + + self._solution = { + "installed_add_on_sid": installed_add_on_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 InstalledAddOnUsageList(ListResource): + + class MarketplaceV1InstalledAddOnInstalledAddOnUsage(object): + """ + :ivar total_submitted: Total amount in local currency that was billed in this request. Aggregates all billable_items that were successfully submitted. + :ivar billable_items: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.total_submitted: Optional[float] = deserialize.decimal( + payload.get("total_submitted") + ) + self.billable_items: Optional[ + List[ + InstalledAddOnUsageList.MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems + ] + ] = payload.get("billable_items") + + def to_dict(self): + return { + "total_submitted": self.total_submitted, + "billable_items": ( + [billable_items.to_dict() for billable_items in self.billable_items] + if self.billable_items is not None + else None + ), + } + + class MarketplaceV1InstalledAddOnInstalledAddOnUsageBillableItems(object): + """ + :ivar quantity: Total amount in local currency that was billed for this Billing Item. Can be any floating number greater than 0. + :ivar sid: BillingSid to use for billing. + :ivar submitted: Whether the billing event was successfully generated for this Billable Item. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.quantity: Optional[float] = payload.get("quantity") + self.sid: Optional[str] = payload.get("sid") + self.submitted: Optional[bool] = payload.get("submitted") + + def to_dict(self): + return { + "quantity": self.quantity, + "sid": self.sid, + "submitted": self.submitted, + } + + def __init__(self, version: Version, installed_add_on_sid: str): + """ + Initialize the InstalledAddOnUsageList + + :param version: Version that contains the resource + :param installed_add_on_sid: Customer Installation SID to report usage on. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "installed_add_on_sid": installed_add_on_sid, + } + self._uri = "/InstalledAddOns/{installed_add_on_sid}/Usage".format( + **self._solution + ) + + def _create( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = marketplace_v1_installed_add_on_installed_add_on_usage.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, + 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"], + ) + + def create_with_http_info( + self, + marketplace_v1_installed_add_on_installed_add_on_usage: MarketplaceV1InstalledAddOnInstalledAddOnUsage, + ) -> ApiResponse: + """ + 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 = 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() + + 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, + 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/marketplace/v1/module_data.py b/twilio/rest/marketplace/v1/module_data.py new file mode 100644 index 0000000000..90a6cbb99a --- /dev/null +++ b/twilio/rest/marketplace/v1/module_data.py @@ -0,0 +1,283 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + 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 ModuleDataInstance(InstanceResource): + """ + :ivar url: URL to query the subresource. + :ivar sid: ModuleSid that identifies this Listing. + :ivar description: A JSON object describing the module and is displayed under the Description tab of the Module detail page. You can define the main body of the description, highlight key features or aspects of the module and if applicable, provide code samples for developers + :ivar support: A JSON object containing information on how customers can obtain support for the module. Use this parameter to provide details such as contact information and support description. + :ivar policies: A JSON object describing the module's privacy and legal policies and is displayed under the Policies tab of the Module detail page. The maximum file size for Policies is 5MB + :ivar module_info: A JSON object containing essential attributes that define a module. This information is presented on the Module detail page in the Twilio Marketplace Catalog. You can pass the following attributes in the JSON object + :ivar documentation: A JSON object for providing comprehensive information, instructions, and resources related to the module + :ivar configuration: A JSON object for providing listing specific configuration. Contains button setup, notification url, among others. + :ivar pricing: A JSON object for providing Listing specific pricing information. + :ivar listings: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.description: Optional[Dict[str, object]] = payload.get("description") + self.support: Optional[Dict[str, object]] = payload.get("support") + self.policies: Optional[Dict[str, object]] = payload.get("policies") + self.module_info: Optional[Dict[str, object]] = payload.get("module_info") + self.documentation: Optional[Dict[str, object]] = payload.get("documentation") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.pricing: Optional[Dict[str, object]] = payload.get("pricing") + self.listings: Optional[List[Dict[str, object]]] = payload.get("listings") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ModuleDataList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ModuleDataList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Listings" + + def _create( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Configuration": 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, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> 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( + { + "ModuleInfo": module_info, + "Configuration": 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, + 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) + + async def create_with_http_info_async( + self, + module_info: Union[str, object] = values.unset, + configuration: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + 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: 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" + + 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) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ModuleDataInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/marketplace/v1/module_data_management.py b/twilio/rest/marketplace/v1/module_data_management.py new file mode 100644 index 0000000000..6ac9e02d46 --- /dev/null +++ b/twilio/rest/marketplace/v1/module_data_management.py @@ -0,0 +1,625 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + 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_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class ModuleDataManagementInstance(InstanceResource): + """ + :ivar url: URL to query the subresource. + :ivar sid: ModuleSid that identifies this Listing. + :ivar description: A JSON object describing the module and is displayed under the Description tab of the Module detail page. You can define the main body of the description, highlight key features or aspects of the module and if applicable, provide code samples for developers + :ivar support: A JSON object containing information on how customers can obtain support for the module. Use this parameter to provide details such as contact information and support description. + :ivar policies: A JSON object describing the module's privacy and legal policies and is displayed under the Policies tab of the Module detail page. The maximum file size for Policies is 5MB + :ivar module_info: A JSON object containing essential attributes that define a module. This information is presented on the Module detail page in the Twilio Marketplace Catalog. You can pass the following attributes in the JSON object + :ivar documentation: A JSON object for providing comprehensive information, instructions, and resources related to the module + :ivar configuration: A JSON object for providing listing specific configuration. Contains button setup, notification url, among others. + :ivar pricing: A JSON object for providing Listing specific pricing information. + :ivar listings: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None + ): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.sid: Optional[str] = payload.get("sid") + self.description: Optional[Dict[str, object]] = payload.get("description") + self.support: Optional[Dict[str, object]] = payload.get("support") + self.policies: Optional[Dict[str, object]] = payload.get("policies") + self.module_info: Optional[Dict[str, object]] = payload.get("module_info") + self.documentation: Optional[Dict[str, object]] = payload.get("documentation") + self.configuration: Optional[Dict[str, object]] = payload.get("configuration") + self.pricing: Optional[Dict[str, object]] = payload.get("pricing") + self.listings: Optional[List[Dict[str, object]]] = payload.get("listings") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[ModuleDataManagementContext] = None + + @property + def _proxy(self) -> "ModuleDataManagementContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ModuleDataManagementContext for this ModuleDataManagementInstance + """ + if self._context is None: + self._context = ModuleDataManagementContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def fetch(self) -> "ModuleDataManagementInstance": + """ + Fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ModuleDataManagementInstance": + """ + Asynchronous coroutine to fetch the ModuleDataManagementInstance + + + :returns: The fetched 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, + 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 + """ + return self._proxy.update( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + pricing=pricing, + ) + + 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 + """ + return await self._proxy.update_async( + module_info=module_info, + description=description, + documentation=documentation, + policies=policies, + support=support, + configuration=configuration, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ModuleDataManagementContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the ModuleDataManagementContext + + :param version: Version that contains the resource + :param sid: SID that uniquely identifies the Listing. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Listing/{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) -> ModuleDataManagementInstance: + """ + Fetch the ModuleDataManagementInstance + + + :returns: The fetched ModuleDataManagementInstance + """ + payload, _, _ = self._fetch() + return ModuleDataManagementInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ModuleDataManagementInstance and return response metadata + + + :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" + + 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"], + ) + + 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, + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "ModuleInfo": module_info, + "Description": description, + "Documentation": documentation, + "Policies": policies, + "Support": support, + "Configuration": configuration, + "Pricing": pricing, + } + ) + 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, + 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"] + ) + + 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 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 = 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( + { + "ModuleInfo": module_info, + "Description": description, + "Documentation": documentation, + "Policies": policies, + "Support": support, + "Configuration": configuration, + "Pricing": pricing, + } + ) + 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, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ModuleDataManagementList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ModuleDataManagementList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, sid: str) -> ModuleDataManagementContext: + """ + Constructs a ModuleDataManagementContext + + :param sid: SID that uniquely identifies the Listing. + """ + return ModuleDataManagementContext(self._version, sid=sid) + + def __call__(self, sid: str) -> ModuleDataManagementContext: + """ + Constructs a ModuleDataManagementContext + + :param sid: SID that uniquely identifies the Listing. + """ + return ModuleDataManagementContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/marketplace/v1/referral_conversion.py b/twilio/rest/marketplace/v1/referral_conversion.py new file mode 100644 index 0000000000..1234b45c6f --- /dev/null +++ b/twilio/rest/marketplace/v1/referral_conversion.py @@ -0,0 +1,200 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Marketplace + 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 ReferralConversionInstance(InstanceResource): + + class CreateReferralConversionRequest(object): + """ + :ivar referral_account_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.referral_account_sid: Optional[str] = payload.get( + "referral_account_sid" + ) + + def to_dict(self): + return { + "referral_account_sid": self.referral_account_sid, + } + + """ + :ivar converted_account_sid: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.converted_account_sid: Optional[str] = payload.get("converted_account_sid") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ReferralConversionList(ListResource): + + class CreateReferralConversionRequest(object): + """ + :ivar referral_account_sid: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.referral_account_sid: Optional[str] = payload.get( + "referral_account_sid" + ) + + def to_dict(self): + return { + "referral_account_sid": self.referral_account_sid, + } + + def __init__(self, version: Version): + """ + Initialize the ReferralConversionList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ReferralConversion" + + def _create( + self, create_referral_conversion_request: CreateReferralConversionRequest + ) -> tuple: + """ + Internal 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"}) + + 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_referral_conversion_request: CreateReferralConversionRequest + ) -> 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"}) + + 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_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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/media/__init__.py b/twilio/rest/media/__init__.py deleted file mode 100644 index ce6207e29a..0000000000 --- a/twilio/rest/media/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -from warnings import warn - -from twilio.rest.media.MediaBase import MediaBase -from twilio.rest.media.v1.media_processor import MediaProcessorList -from twilio.rest.media.v1.media_recording import MediaRecordingList -from twilio.rest.media.v1.player_streamer import PlayerStreamerList - - -class Media(MediaBase): - @property - def media_processor(self) -> MediaProcessorList: - warn( - "media_processor is deprecated. Use v1.media_processor instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.media_processor - - @property - def media_recording(self) -> MediaRecordingList: - warn( - "media_recording is deprecated. Use v1.media_recording instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.media_recording - - @property - def player_streamer(self) -> PlayerStreamerList: - warn( - "player_streamer is deprecated. Use v1.player_streamer instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.player_streamer diff --git a/twilio/rest/media/v1/__init__.py b/twilio/rest/media/v1/__init__.py deleted file mode 100644 index cca96fc012..0000000000 --- a/twilio/rest/media/v1/__init__.py +++ /dev/null @@ -1,58 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Media - 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.media.v1.media_processor import MediaProcessorList -from twilio.rest.media.v1.media_recording import MediaRecordingList -from twilio.rest.media.v1.player_streamer import PlayerStreamerList - - -class V1(Version): - def __init__(self, domain: Domain): - """ - Initialize the V1 version of Media - - :param domain: The Twilio.media domain - """ - super().__init__(domain, "v1") - self._media_processor: Optional[MediaProcessorList] = None - self._media_recording: Optional[MediaRecordingList] = None - self._player_streamer: Optional[PlayerStreamerList] = None - - @property - def media_processor(self) -> MediaProcessorList: - if self._media_processor is None: - self._media_processor = MediaProcessorList(self) - return self._media_processor - - @property - def media_recording(self) -> MediaRecordingList: - if self._media_recording is None: - self._media_recording = MediaRecordingList(self) - return self._media_recording - - @property - def player_streamer(self) -> PlayerStreamerList: - if self._player_streamer is None: - self._player_streamer = PlayerStreamerList(self) - return self._player_streamer - - def __repr__(self) -> str: - """ - Provide a friendly representation - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/media/v1/media_processor.py b/twilio/rest/media/v1/media_processor.py deleted file mode 100644 index f136619d6c..0000000000 --- a/twilio/rest/media/v1/media_processor.py +++ /dev/null @@ -1,617 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Media - 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 MediaProcessorInstance(InstanceResource): - class Order(object): - ASC = "asc" - DESC = "desc" - - class Status(object): - FAILED = "failed" - STARTED = "started" - ENDED = "ended" - - class UpdateStatus(object): - ENDED = "ended" - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the MediaProcessor resource. - :ivar sid: The unique string generated to identify the MediaProcessor resource. - :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 extension: The [Media Extension](/docs/live/api/media-extensions-overview) name or URL. Ex: `video-composer-v2` - :ivar extension_context: The context of the Media Extension, represented as a JSON dictionary. See the documentation for the specific [Media Extension](/docs/live/api/media-extensions-overview) you are using for more information about the context to send. - :ivar status: - :ivar url: The absolute URL of the resource. - :ivar ended_reason: The reason why a MediaProcessor ended. When a MediaProcessor is in progress, will be `null`. When a MediaProcessor is completed, can be `ended-via-api`, `max-duration-exceeded`, `error-loading-extension`, `error-streaming-media` or `internal-service-error`. See [ended reasons](/docs/live/api/mediaprocessors#mediaprocessor-ended-reason-values) for more details. - :ivar status_callback: The URL to which Twilio will send asynchronous webhook requests for every MediaProcessor event. See [Status Callbacks](/docs/live/status-callbacks) for details. - :ivar status_callback_method: The HTTP method Twilio should use to call the `status_callback` URL. Can be `POST` or `GET` and the default is `POST`. - :ivar max_duration: The maximum time, in seconds, that the MediaProcessor can run before automatically ends. The default value is 300 seconds, and the maximum value is 90000 seconds. Once this maximum duration is reached, Twilio will end the MediaProcessor, regardless of whether media is still streaming. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.sid: Optional[str] = payload.get("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.extension: Optional[str] = payload.get("extension") - self.extension_context: Optional[str] = payload.get("extension_context") - self.status: Optional["MediaProcessorInstance.Status"] = payload.get("status") - self.url: Optional[str] = payload.get("url") - self.ended_reason: Optional[str] = payload.get("ended_reason") - self.status_callback: Optional[str] = payload.get("status_callback") - self.status_callback_method: Optional[str] = payload.get( - "status_callback_method" - ) - self.max_duration: Optional[int] = deserialize.integer( - payload.get("max_duration") - ) - - self._solution = { - "sid": sid or self.sid, - } - self._context: Optional[MediaProcessorContext] = None - - @property - def _proxy(self) -> "MediaProcessorContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: MediaProcessorContext for this MediaProcessorInstance - """ - if self._context is None: - self._context = MediaProcessorContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def fetch(self) -> "MediaProcessorInstance": - """ - Fetch the MediaProcessorInstance - - - :returns: The fetched MediaProcessorInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "MediaProcessorInstance": - """ - Asynchronous coroutine to fetch the MediaProcessorInstance - - - :returns: The fetched MediaProcessorInstance - """ - return await self._proxy.fetch_async() - - def update( - self, status: "MediaProcessorInstance.UpdateStatus" - ) -> "MediaProcessorInstance": - """ - Update the MediaProcessorInstance - - :param status: - - :returns: The updated MediaProcessorInstance - """ - return self._proxy.update( - status=status, - ) - - async def update_async( - self, status: "MediaProcessorInstance.UpdateStatus" - ) -> "MediaProcessorInstance": - """ - Asynchronous coroutine to update the MediaProcessorInstance - - :param status: - - :returns: The updated MediaProcessorInstance - """ - return await self._proxy.update_async( - status=status, - ) - - 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 MediaProcessorContext(InstanceContext): - def __init__(self, version: Version, sid: str): - """ - Initialize the MediaProcessorContext - - :param version: Version that contains the resource - :param sid: The SID of the MediaProcessor resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/MediaProcessors/{sid}".format(**self._solution) - - def fetch(self) -> MediaProcessorInstance: - """ - Fetch the MediaProcessorInstance - - - :returns: The fetched MediaProcessorInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return MediaProcessorInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> MediaProcessorInstance: - """ - Asynchronous coroutine to fetch the MediaProcessorInstance - - - :returns: The fetched MediaProcessorInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return MediaProcessorInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( - self, status: "MediaProcessorInstance.UpdateStatus" - ) -> MediaProcessorInstance: - """ - Update the MediaProcessorInstance - - :param status: - - :returns: The updated MediaProcessorInstance - """ - data = values.of( - { - "Status": status, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return MediaProcessorInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( - self, status: "MediaProcessorInstance.UpdateStatus" - ) -> MediaProcessorInstance: - """ - Asynchronous coroutine to update the MediaProcessorInstance - - :param status: - - :returns: The updated MediaProcessorInstance - """ - data = values.of( - { - "Status": status, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return MediaProcessorInstance(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 MediaProcessorPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> MediaProcessorInstance: - """ - Build an instance of MediaProcessorInstance - - :param payload: Payload response from the API - """ - return MediaProcessorInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class MediaProcessorList(ListResource): - def __init__(self, version: Version): - """ - Initialize the MediaProcessorList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/MediaProcessors" - - def create( - self, - extension: str, - extension_context: str, - extension_environment: Union[object, object] = values.unset, - status_callback: Union[str, object] = values.unset, - status_callback_method: Union[str, object] = values.unset, - max_duration: Union[int, object] = values.unset, - ) -> MediaProcessorInstance: - """ - Create the MediaProcessorInstance - - :param extension: The [Media Extension](/docs/live/api/media-extensions-overview) name or URL. Ex: `video-composer-v2` - :param extension_context: The context of the Media Extension, represented as a JSON dictionary. See the documentation for the specific [Media Extension](/docs/live/api/media-extensions-overview) you are using for more information about the context to send. - :param extension_environment: User-defined environment variables for the Media Extension, represented as a JSON dictionary of key/value strings. See the documentation for the specific [Media Extension](/docs/live/api/media-extensions-overview) you are using for more information about whether you need to provide this. - :param status_callback: The URL to which Twilio will send asynchronous webhook requests for every MediaProcessor event. See [Status Callbacks](/docs/live/status-callbacks) for details. - :param status_callback_method: The HTTP method Twilio should use to call the `status_callback` URL. Can be `POST` or `GET` and the default is `POST`. - :param max_duration: The maximum time, in seconds, that the MediaProcessor can run before automatically ends. The default value is 300 seconds, and the maximum value is 90000 seconds. Once this maximum duration is reached, Twilio will end the MediaProcessor, regardless of whether media is still streaming. - - :returns: The created MediaProcessorInstance - """ - data = values.of( - { - "Extension": extension, - "ExtensionContext": extension_context, - "ExtensionEnvironment": serialize.object(extension_environment), - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "MaxDuration": max_duration, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return MediaProcessorInstance(self._version, payload) - - async def create_async( - self, - extension: str, - extension_context: str, - extension_environment: Union[object, object] = values.unset, - status_callback: Union[str, object] = values.unset, - status_callback_method: Union[str, object] = values.unset, - max_duration: Union[int, object] = values.unset, - ) -> MediaProcessorInstance: - """ - Asynchronously create the MediaProcessorInstance - - :param extension: The [Media Extension](/docs/live/api/media-extensions-overview) name or URL. Ex: `video-composer-v2` - :param extension_context: The context of the Media Extension, represented as a JSON dictionary. See the documentation for the specific [Media Extension](/docs/live/api/media-extensions-overview) you are using for more information about the context to send. - :param extension_environment: User-defined environment variables for the Media Extension, represented as a JSON dictionary of key/value strings. See the documentation for the specific [Media Extension](/docs/live/api/media-extensions-overview) you are using for more information about whether you need to provide this. - :param status_callback: The URL to which Twilio will send asynchronous webhook requests for every MediaProcessor event. See [Status Callbacks](/docs/live/status-callbacks) for details. - :param status_callback_method: The HTTP method Twilio should use to call the `status_callback` URL. Can be `POST` or `GET` and the default is `POST`. - :param max_duration: The maximum time, in seconds, that the MediaProcessor can run before automatically ends. The default value is 300 seconds, and the maximum value is 90000 seconds. Once this maximum duration is reached, Twilio will end the MediaProcessor, regardless of whether media is still streaming. - - :returns: The created MediaProcessorInstance - """ - data = values.of( - { - "Extension": extension, - "ExtensionContext": extension_context, - "ExtensionEnvironment": serialize.object(extension_environment), - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "MaxDuration": max_duration, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return MediaProcessorInstance(self._version, payload) - - def stream( - self, - order: Union["MediaProcessorInstance.Order", object] = values.unset, - status: Union["MediaProcessorInstance.Status", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[MediaProcessorInstance]: - """ - Streams MediaProcessorInstance 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 "MediaProcessorInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "MediaProcessorInstance.Status" status: Status to filter by, with possible values `started`, `ended` 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: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(order=order, status=status, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - order: Union["MediaProcessorInstance.Order", object] = values.unset, - status: Union["MediaProcessorInstance.Status", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[MediaProcessorInstance]: - """ - Asynchronously streams MediaProcessorInstance 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 "MediaProcessorInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "MediaProcessorInstance.Status" status: Status to filter by, with possible values `started`, `ended` 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: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async( - order=order, status=status, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - order: Union["MediaProcessorInstance.Order", object] = values.unset, - status: Union["MediaProcessorInstance.Status", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[MediaProcessorInstance]: - """ - Lists MediaProcessorInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "MediaProcessorInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "MediaProcessorInstance.Status" status: Status to filter by, with possible values `started`, `ended` 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: list that will contain up to limit results - """ - return list( - self.stream( - order=order, - status=status, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - order: Union["MediaProcessorInstance.Order", object] = values.unset, - status: Union["MediaProcessorInstance.Status", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[MediaProcessorInstance]: - """ - Asynchronously lists MediaProcessorInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "MediaProcessorInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "MediaProcessorInstance.Status" status: Status to filter by, with possible values `started`, `ended` 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: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - order=order, - status=status, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - order: Union["MediaProcessorInstance.Order", object] = values.unset, - status: Union["MediaProcessorInstance.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, - ) -> MediaProcessorPage: - """ - Retrieve a single page of MediaProcessorInstance records from the API. - Request is executed immediately - - :param order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param status: Status to filter by, with possible values `started`, `ended` 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: Page of MediaProcessorInstance - """ - data = values.of( - { - "Order": order, - "Status": status, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return MediaProcessorPage(self._version, response) - - async def page_async( - self, - order: Union["MediaProcessorInstance.Order", object] = values.unset, - status: Union["MediaProcessorInstance.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, - ) -> MediaProcessorPage: - """ - Asynchronously retrieve a single page of MediaProcessorInstance records from the API. - Request is executed immediately - - :param order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param status: Status to filter by, with possible values `started`, `ended` 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: Page of MediaProcessorInstance - """ - data = values.of( - { - "Order": order, - "Status": status, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return MediaProcessorPage(self._version, response) - - def get_page(self, target_url: str) -> MediaProcessorPage: - """ - Retrieve a specific page of MediaProcessorInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of MediaProcessorInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return MediaProcessorPage(self._version, response) - - async def get_page_async(self, target_url: str) -> MediaProcessorPage: - """ - Asynchronously retrieve a specific page of MediaProcessorInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of MediaProcessorInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return MediaProcessorPage(self._version, response) - - def get(self, sid: str) -> MediaProcessorContext: - """ - Constructs a MediaProcessorContext - - :param sid: The SID of the MediaProcessor resource to update. - """ - return MediaProcessorContext(self._version, sid=sid) - - def __call__(self, sid: str) -> MediaProcessorContext: - """ - Constructs a MediaProcessorContext - - :param sid: The SID of the MediaProcessor resource to update. - """ - return MediaProcessorContext(self._version, sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/media/v1/media_recording.py b/twilio/rest/media/v1/media_recording.py deleted file mode 100644 index da0ea616dc..0000000000 --- a/twilio/rest/media/v1/media_recording.py +++ /dev/null @@ -1,551 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Media - 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 MediaRecordingInstance(InstanceResource): - class Format(object): - MP4 = "mp4" - WEBM = "webm" - - class Order(object): - ASC = "asc" - DESC = "desc" - - class Status(object): - PROCESSING = "processing" - COMPLETED = "completed" - DELETED = "deleted" - FAILED = "failed" - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the MediaRecording resource. - :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 duration: The duration of the MediaRecording in seconds. - :ivar format: - :ivar links: The URLs of related resources. - :ivar processor_sid: The SID of the MediaProcessor resource which produced the MediaRecording. - :ivar resolution: The dimensions of the video image in pixels expressed as columns (width) and rows (height). - :ivar source_sid: The SID of the resource that generated the original media track(s) of the MediaRecording. - :ivar sid: The unique string generated to identify the MediaRecording resource. - :ivar media_size: The size of the recording media in bytes. - :ivar status: - :ivar status_callback: The URL to which Twilio will send asynchronous webhook requests for every MediaRecording event. See [Status Callbacks](/docs/live/status-callbacks) for more details. - :ivar status_callback_method: The HTTP method Twilio should use to call the `status_callback` URL. Can be `POST` or `GET` and the default is `POST`. - :ivar url: The absolute URL of the resource. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.duration: Optional[int] = deserialize.integer(payload.get("duration")) - self.format: Optional["MediaRecordingInstance.Format"] = payload.get("format") - self.links: Optional[Dict[str, object]] = payload.get("links") - self.processor_sid: Optional[str] = payload.get("processor_sid") - self.resolution: Optional[str] = payload.get("resolution") - self.source_sid: Optional[str] = payload.get("source_sid") - self.sid: Optional[str] = payload.get("sid") - self.media_size: Optional[int] = payload.get("media_size") - self.status: Optional["MediaRecordingInstance.Status"] = payload.get("status") - self.status_callback: Optional[str] = payload.get("status_callback") - self.status_callback_method: Optional[str] = payload.get( - "status_callback_method" - ) - self.url: Optional[str] = payload.get("url") - - self._solution = { - "sid": sid or self.sid, - } - self._context: Optional[MediaRecordingContext] = None - - @property - def _proxy(self) -> "MediaRecordingContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: MediaRecordingContext for this MediaRecordingInstance - """ - if self._context is None: - self._context = MediaRecordingContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the MediaRecordingInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the MediaRecordingInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "MediaRecordingInstance": - """ - Fetch the MediaRecordingInstance - - - :returns: The fetched MediaRecordingInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "MediaRecordingInstance": - """ - Asynchronous coroutine to fetch the MediaRecordingInstance - - - :returns: The fetched MediaRecordingInstance - """ - 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 "".format(context) - - -class MediaRecordingContext(InstanceContext): - def __init__(self, version: Version, sid: str): - """ - Initialize the MediaRecordingContext - - :param version: Version that contains the resource - :param sid: The SID of the MediaRecording resource to fetch. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/MediaRecordings/{sid}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the MediaRecordingInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the MediaRecordingInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> MediaRecordingInstance: - """ - Fetch the MediaRecordingInstance - - - :returns: The fetched MediaRecordingInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return MediaRecordingInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> MediaRecordingInstance: - """ - Asynchronous coroutine to fetch the MediaRecordingInstance - - - :returns: The fetched MediaRecordingInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return MediaRecordingInstance( - 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 MediaRecordingPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> MediaRecordingInstance: - """ - Build an instance of MediaRecordingInstance - - :param payload: Payload response from the API - """ - return MediaRecordingInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class MediaRecordingList(ListResource): - def __init__(self, version: Version): - """ - Initialize the MediaRecordingList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/MediaRecordings" - - def stream( - self, - order: Union["MediaRecordingInstance.Order", object] = values.unset, - status: Union["MediaRecordingInstance.Status", object] = values.unset, - processor_sid: Union[str, object] = values.unset, - source_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[MediaRecordingInstance]: - """ - Streams MediaRecordingInstance 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 "MediaRecordingInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "MediaRecordingInstance.Status" status: Status to filter by, with possible values `processing`, `completed`, `deleted`, or `failed`. - :param str processor_sid: SID of a MediaProcessor to filter by. - :param str source_sid: SID of a MediaRecording source 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( - order=order, - status=status, - processor_sid=processor_sid, - source_sid=source_sid, - page_size=limits["page_size"], - ) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - order: Union["MediaRecordingInstance.Order", object] = values.unset, - status: Union["MediaRecordingInstance.Status", object] = values.unset, - processor_sid: Union[str, object] = values.unset, - source_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[MediaRecordingInstance]: - """ - Asynchronously streams MediaRecordingInstance 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 "MediaRecordingInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "MediaRecordingInstance.Status" status: Status to filter by, with possible values `processing`, `completed`, `deleted`, or `failed`. - :param str processor_sid: SID of a MediaProcessor to filter by. - :param str source_sid: SID of a MediaRecording source 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( - order=order, - status=status, - processor_sid=processor_sid, - source_sid=source_sid, - page_size=limits["page_size"], - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - order: Union["MediaRecordingInstance.Order", object] = values.unset, - status: Union["MediaRecordingInstance.Status", object] = values.unset, - processor_sid: Union[str, object] = values.unset, - source_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[MediaRecordingInstance]: - """ - Lists MediaRecordingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "MediaRecordingInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "MediaRecordingInstance.Status" status: Status to filter by, with possible values `processing`, `completed`, `deleted`, or `failed`. - :param str processor_sid: SID of a MediaProcessor to filter by. - :param str source_sid: SID of a MediaRecording source 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( - order=order, - status=status, - processor_sid=processor_sid, - source_sid=source_sid, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - order: Union["MediaRecordingInstance.Order", object] = values.unset, - status: Union["MediaRecordingInstance.Status", object] = values.unset, - processor_sid: Union[str, object] = values.unset, - source_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[MediaRecordingInstance]: - """ - Asynchronously lists MediaRecordingInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "MediaRecordingInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "MediaRecordingInstance.Status" status: Status to filter by, with possible values `processing`, `completed`, `deleted`, or `failed`. - :param str processor_sid: SID of a MediaProcessor to filter by. - :param str source_sid: SID of a MediaRecording source 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( - order=order, - status=status, - processor_sid=processor_sid, - source_sid=source_sid, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - order: Union["MediaRecordingInstance.Order", object] = values.unset, - status: Union["MediaRecordingInstance.Status", object] = values.unset, - processor_sid: 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, - ) -> MediaRecordingPage: - """ - Retrieve a single page of MediaRecordingInstance records from the API. - Request is executed immediately - - :param order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param status: Status to filter by, with possible values `processing`, `completed`, `deleted`, or `failed`. - :param processor_sid: SID of a MediaProcessor to filter by. - :param source_sid: SID of a MediaRecording source 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 MediaRecordingInstance - """ - data = values.of( - { - "Order": order, - "Status": status, - "ProcessorSid": processor_sid, - "SourceSid": source_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return MediaRecordingPage(self._version, response) - - async def page_async( - self, - order: Union["MediaRecordingInstance.Order", object] = values.unset, - status: Union["MediaRecordingInstance.Status", object] = values.unset, - processor_sid: 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, - ) -> MediaRecordingPage: - """ - Asynchronously retrieve a single page of MediaRecordingInstance records from the API. - Request is executed immediately - - :param order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param status: Status to filter by, with possible values `processing`, `completed`, `deleted`, or `failed`. - :param processor_sid: SID of a MediaProcessor to filter by. - :param source_sid: SID of a MediaRecording source 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 MediaRecordingInstance - """ - data = values.of( - { - "Order": order, - "Status": status, - "ProcessorSid": processor_sid, - "SourceSid": source_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return MediaRecordingPage(self._version, response) - - def get_page(self, target_url: str) -> MediaRecordingPage: - """ - Retrieve a specific page of MediaRecordingInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of MediaRecordingInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return MediaRecordingPage(self._version, response) - - async def get_page_async(self, target_url: str) -> MediaRecordingPage: - """ - Asynchronously retrieve a specific page of MediaRecordingInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of MediaRecordingInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return MediaRecordingPage(self._version, response) - - def get(self, sid: str) -> MediaRecordingContext: - """ - Constructs a MediaRecordingContext - - :param sid: The SID of the MediaRecording resource to fetch. - """ - return MediaRecordingContext(self._version, sid=sid) - - def __call__(self, sid: str) -> MediaRecordingContext: - """ - Constructs a MediaRecordingContext - - :param sid: The SID of the MediaRecording resource to fetch. - """ - return MediaRecordingContext(self._version, sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/media/v1/player_streamer/__init__.py b/twilio/rest/media/v1/player_streamer/__init__.py deleted file mode 100644 index 80946e466e..0000000000 --- a/twilio/rest/media/v1/player_streamer/__init__.py +++ /dev/null @@ -1,636 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Media - 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.media.v1.player_streamer.playback_grant import PlaybackGrantList - - -class PlayerStreamerInstance(InstanceResource): - class EndedReason(object): - ENDED_VIA_API = "ended-via-api" - MAX_DURATION_EXCEEDED = "max-duration-exceeded" - STREAM_DISCONNECTED_BY_SOURCE = "stream-disconnected-by-source" - UNEXPECTED_FAILURE = "unexpected-failure" - - class Order(object): - ASC = "asc" - DESC = "desc" - - class Status(object): - CREATED = "created" - STARTED = "started" - ENDED = "ended" - FAILED = "failed" - - class UpdateStatus(object): - ENDED = "ended" - - """ - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PlayerStreamer resource. - :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 video: Specifies whether the PlayerStreamer is configured to stream video. Defaults to `true`. - :ivar links: The URLs of related resources. - :ivar sid: The unique string generated to identify the PlayerStreamer resource. - :ivar status: - :ivar url: The absolute URL of the resource. - :ivar status_callback: The URL to which Twilio will send asynchronous webhook requests for every PlayerStreamer event. See [Status Callbacks](/docs/live/status-callbacks) for more details. - :ivar status_callback_method: The HTTP method Twilio should use to call the `status_callback` URL. Can be `POST` or `GET` and the default is `POST`. - :ivar ended_reason: - :ivar max_duration: The maximum time, in seconds, that the PlayerStreamer is active (`created` or `started`) before automatically ends. The default value is 300 seconds, and the maximum value is 90000 seconds. Once this maximum duration is reached, Twilio will end the PlayerStreamer, regardless of whether media is still streaming. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.video: Optional[bool] = payload.get("video") - self.links: Optional[Dict[str, object]] = payload.get("links") - self.sid: Optional[str] = payload.get("sid") - self.status: Optional["PlayerStreamerInstance.Status"] = payload.get("status") - self.url: Optional[str] = payload.get("url") - self.status_callback: Optional[str] = payload.get("status_callback") - self.status_callback_method: Optional[str] = payload.get( - "status_callback_method" - ) - self.ended_reason: Optional["PlayerStreamerInstance.EndedReason"] = payload.get( - "ended_reason" - ) - self.max_duration: Optional[int] = deserialize.integer( - payload.get("max_duration") - ) - - self._solution = { - "sid": sid or self.sid, - } - self._context: Optional[PlayerStreamerContext] = None - - @property - def _proxy(self) -> "PlayerStreamerContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: PlayerStreamerContext for this PlayerStreamerInstance - """ - if self._context is None: - self._context = PlayerStreamerContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def fetch(self) -> "PlayerStreamerInstance": - """ - Fetch the PlayerStreamerInstance - - - :returns: The fetched PlayerStreamerInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "PlayerStreamerInstance": - """ - Asynchronous coroutine to fetch the PlayerStreamerInstance - - - :returns: The fetched PlayerStreamerInstance - """ - return await self._proxy.fetch_async() - - def update( - self, status: "PlayerStreamerInstance.UpdateStatus" - ) -> "PlayerStreamerInstance": - """ - Update the PlayerStreamerInstance - - :param status: - - :returns: The updated PlayerStreamerInstance - """ - return self._proxy.update( - status=status, - ) - - async def update_async( - self, status: "PlayerStreamerInstance.UpdateStatus" - ) -> "PlayerStreamerInstance": - """ - Asynchronous coroutine to update the PlayerStreamerInstance - - :param status: - - :returns: The updated PlayerStreamerInstance - """ - return await self._proxy.update_async( - status=status, - ) - - @property - def playback_grant(self) -> PlaybackGrantList: - """ - Access the playback_grant - """ - return self._proxy.playback_grant - - 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 PlayerStreamerContext(InstanceContext): - def __init__(self, version: Version, sid: str): - """ - Initialize the PlayerStreamerContext - - :param version: Version that contains the resource - :param sid: The SID of the PlayerStreamer resource to update. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/PlayerStreamers/{sid}".format(**self._solution) - - self._playback_grant: Optional[PlaybackGrantList] = None - - def fetch(self) -> PlayerStreamerInstance: - """ - Fetch the PlayerStreamerInstance - - - :returns: The fetched PlayerStreamerInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return PlayerStreamerInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> PlayerStreamerInstance: - """ - Asynchronous coroutine to fetch the PlayerStreamerInstance - - - :returns: The fetched PlayerStreamerInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return PlayerStreamerInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( - self, status: "PlayerStreamerInstance.UpdateStatus" - ) -> PlayerStreamerInstance: - """ - Update the PlayerStreamerInstance - - :param status: - - :returns: The updated PlayerStreamerInstance - """ - data = values.of( - { - "Status": status, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return PlayerStreamerInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( - self, status: "PlayerStreamerInstance.UpdateStatus" - ) -> PlayerStreamerInstance: - """ - Asynchronous coroutine to update the PlayerStreamerInstance - - :param status: - - :returns: The updated PlayerStreamerInstance - """ - data = values.of( - { - "Status": status, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return PlayerStreamerInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def playback_grant(self) -> PlaybackGrantList: - """ - Access the playback_grant - """ - if self._playback_grant is None: - self._playback_grant = PlaybackGrantList( - self._version, - self._solution["sid"], - ) - return self._playback_grant - - 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 PlayerStreamerPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> PlayerStreamerInstance: - """ - Build an instance of PlayerStreamerInstance - - :param payload: Payload response from the API - """ - return PlayerStreamerInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class PlayerStreamerList(ListResource): - def __init__(self, version: Version): - """ - Initialize the PlayerStreamerList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/PlayerStreamers" - - def create( - self, - video: Union[bool, object] = values.unset, - status_callback: Union[str, object] = values.unset, - status_callback_method: Union[str, object] = values.unset, - max_duration: Union[int, object] = values.unset, - ) -> PlayerStreamerInstance: - """ - Create the PlayerStreamerInstance - - :param video: Specifies whether the PlayerStreamer is configured to stream video. Defaults to `true`. - :param status_callback: The URL to which Twilio will send asynchronous webhook requests for every PlayerStreamer event. See [Status Callbacks](/docs/live/status-callbacks) for more details. - :param status_callback_method: The HTTP method Twilio should use to call the `status_callback` URL. Can be `POST` or `GET` and the default is `POST`. - :param max_duration: The maximum time, in seconds, that the PlayerStreamer is active (`created` or `started`) before automatically ends. The default value is 300 seconds, and the maximum value is 90000 seconds. Once this maximum duration is reached, Twilio will end the PlayerStreamer, regardless of whether media is still streaming. - - :returns: The created PlayerStreamerInstance - """ - data = values.of( - { - "Video": video, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "MaxDuration": max_duration, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return PlayerStreamerInstance(self._version, payload) - - async def create_async( - self, - video: Union[bool, object] = values.unset, - status_callback: Union[str, object] = values.unset, - status_callback_method: Union[str, object] = values.unset, - max_duration: Union[int, object] = values.unset, - ) -> PlayerStreamerInstance: - """ - Asynchronously create the PlayerStreamerInstance - - :param video: Specifies whether the PlayerStreamer is configured to stream video. Defaults to `true`. - :param status_callback: The URL to which Twilio will send asynchronous webhook requests for every PlayerStreamer event. See [Status Callbacks](/docs/live/status-callbacks) for more details. - :param status_callback_method: The HTTP method Twilio should use to call the `status_callback` URL. Can be `POST` or `GET` and the default is `POST`. - :param max_duration: The maximum time, in seconds, that the PlayerStreamer is active (`created` or `started`) before automatically ends. The default value is 300 seconds, and the maximum value is 90000 seconds. Once this maximum duration is reached, Twilio will end the PlayerStreamer, regardless of whether media is still streaming. - - :returns: The created PlayerStreamerInstance - """ - data = values.of( - { - "Video": video, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "MaxDuration": max_duration, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return PlayerStreamerInstance(self._version, payload) - - def stream( - self, - order: Union["PlayerStreamerInstance.Order", object] = values.unset, - status: Union["PlayerStreamerInstance.Status", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[PlayerStreamerInstance]: - """ - Streams PlayerStreamerInstance 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 "PlayerStreamerInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "PlayerStreamerInstance.Status" status: Status to filter by, with possible values `created`, `started`, `ended`, 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: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = self.page(order=order, status=status, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - order: Union["PlayerStreamerInstance.Order", object] = values.unset, - status: Union["PlayerStreamerInstance.Status", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[PlayerStreamerInstance]: - """ - Asynchronously streams PlayerStreamerInstance 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 "PlayerStreamerInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "PlayerStreamerInstance.Status" status: Status to filter by, with possible values `created`, `started`, `ended`, 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: Generator that will yield up to limit results - """ - limits = self._version.read_limits(limit, page_size) - page = await self.page_async( - order=order, status=status, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - order: Union["PlayerStreamerInstance.Order", object] = values.unset, - status: Union["PlayerStreamerInstance.Status", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[PlayerStreamerInstance]: - """ - Lists PlayerStreamerInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "PlayerStreamerInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "PlayerStreamerInstance.Status" status: Status to filter by, with possible values `created`, `started`, `ended`, 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: list that will contain up to limit results - """ - return list( - self.stream( - order=order, - status=status, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - order: Union["PlayerStreamerInstance.Order", object] = values.unset, - status: Union["PlayerStreamerInstance.Status", object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[PlayerStreamerInstance]: - """ - Asynchronously lists PlayerStreamerInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param "PlayerStreamerInstance.Order" order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param "PlayerStreamerInstance.Status" status: Status to filter by, with possible values `created`, `started`, `ended`, 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: list that will contain up to limit results - """ - return [ - record - async for record in await self.stream_async( - order=order, - status=status, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - order: Union["PlayerStreamerInstance.Order", object] = values.unset, - status: Union["PlayerStreamerInstance.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, - ) -> PlayerStreamerPage: - """ - Retrieve a single page of PlayerStreamerInstance records from the API. - Request is executed immediately - - :param order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param status: Status to filter by, with possible values `created`, `started`, `ended`, 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: Page of PlayerStreamerInstance - """ - data = values.of( - { - "Order": order, - "Status": status, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return PlayerStreamerPage(self._version, response) - - async def page_async( - self, - order: Union["PlayerStreamerInstance.Order", object] = values.unset, - status: Union["PlayerStreamerInstance.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, - ) -> PlayerStreamerPage: - """ - Asynchronously retrieve a single page of PlayerStreamerInstance records from the API. - Request is executed immediately - - :param order: The sort order of the list by `date_created`. Can be: `asc` (ascending) or `desc` (descending) with `desc` as the default. - :param status: Status to filter by, with possible values `created`, `started`, `ended`, 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: Page of PlayerStreamerInstance - """ - data = values.of( - { - "Order": order, - "Status": status, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return PlayerStreamerPage(self._version, response) - - def get_page(self, target_url: str) -> PlayerStreamerPage: - """ - Retrieve a specific page of PlayerStreamerInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of PlayerStreamerInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return PlayerStreamerPage(self._version, response) - - async def get_page_async(self, target_url: str) -> PlayerStreamerPage: - """ - Asynchronously retrieve a specific page of PlayerStreamerInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of PlayerStreamerInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return PlayerStreamerPage(self._version, response) - - def get(self, sid: str) -> PlayerStreamerContext: - """ - Constructs a PlayerStreamerContext - - :param sid: The SID of the PlayerStreamer resource to update. - """ - return PlayerStreamerContext(self._version, sid=sid) - - def __call__(self, sid: str) -> PlayerStreamerContext: - """ - Constructs a PlayerStreamerContext - - :param sid: The SID of the PlayerStreamer resource to update. - """ - return PlayerStreamerContext(self._version, sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/media/v1/player_streamer/playback_grant.py b/twilio/rest/media/v1/player_streamer/playback_grant.py deleted file mode 100644 index 4ea581b474..0000000000 --- a/twilio/rest/media/v1/player_streamer/playback_grant.py +++ /dev/null @@ -1,280 +0,0 @@ -r""" - This code was generated by - ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ - | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ - | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - - Twilio - Media - 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.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 PlaybackGrantInstance(InstanceResource): - - """ - :ivar sid: The unique string generated to identify the PlayerStreamer resource that this PlaybackGrant authorizes views for. - :ivar url: The absolute URL of the resource. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created this resource. - :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 grant: The grant that authorizes the player sdk to connect to the livestream - """ - - def __init__(self, version: Version, payload: Dict[str, Any], sid: str): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.url: Optional[str] = payload.get("url") - self.account_sid: Optional[str] = payload.get("account_sid") - self.date_created: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_created") - ) - self.grant: Optional[Dict[str, object]] = payload.get("grant") - - self._solution = { - "sid": sid, - } - self._context: Optional[PlaybackGrantContext] = None - - @property - def _proxy(self) -> "PlaybackGrantContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: PlaybackGrantContext for this PlaybackGrantInstance - """ - if self._context is None: - self._context = PlaybackGrantContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def create( - self, - ttl: Union[int, object] = values.unset, - access_control_allow_origin: Union[str, object] = values.unset, - ) -> "PlaybackGrantInstance": - """ - Create the PlaybackGrantInstance - - :param ttl: The time to live of the PlaybackGrant. Default value is 15 seconds. Maximum value is 60 seconds. - :param access_control_allow_origin: The full origin URL where the livestream can be streamed. If this is not provided, it can be streamed from any domain. - - :returns: The created PlaybackGrantInstance - """ - return self._proxy.create( - ttl=ttl, - access_control_allow_origin=access_control_allow_origin, - ) - - async def create_async( - self, - ttl: Union[int, object] = values.unset, - access_control_allow_origin: Union[str, object] = values.unset, - ) -> "PlaybackGrantInstance": - """ - Asynchronous coroutine to create the PlaybackGrantInstance - - :param ttl: The time to live of the PlaybackGrant. Default value is 15 seconds. Maximum value is 60 seconds. - :param access_control_allow_origin: The full origin URL where the livestream can be streamed. If this is not provided, it can be streamed from any domain. - - :returns: The created PlaybackGrantInstance - """ - return await self._proxy.create_async( - ttl=ttl, - access_control_allow_origin=access_control_allow_origin, - ) - - def fetch(self) -> "PlaybackGrantInstance": - """ - Fetch the PlaybackGrantInstance - - - :returns: The fetched PlaybackGrantInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "PlaybackGrantInstance": - """ - Asynchronous coroutine to fetch the PlaybackGrantInstance - - - :returns: The fetched PlaybackGrantInstance - """ - 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 "".format(context) - - -class PlaybackGrantContext(InstanceContext): - def __init__(self, version: Version, sid: str): - """ - Initialize the PlaybackGrantContext - - :param version: Version that contains the resource - :param sid: The SID of the PlayerStreamer resource to fetch. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/PlayerStreamers/{sid}/PlaybackGrant".format(**self._solution) - - def create( - self, - ttl: Union[int, object] = values.unset, - access_control_allow_origin: Union[str, object] = values.unset, - ) -> PlaybackGrantInstance: - """ - Create the PlaybackGrantInstance - - :param ttl: The time to live of the PlaybackGrant. Default value is 15 seconds. Maximum value is 60 seconds. - :param access_control_allow_origin: The full origin URL where the livestream can be streamed. If this is not provided, it can be streamed from any domain. - - :returns: The created PlaybackGrantInstance - """ - data = values.of( - { - "Ttl": ttl, - "AccessControlAllowOrigin": access_control_allow_origin, - } - ) - - payload = self._version.create(method="POST", uri=self._uri, data=data) - - return PlaybackGrantInstance(self._version, payload, sid=self._solution["sid"]) - - async def create_async( - self, - ttl: Union[int, object] = values.unset, - access_control_allow_origin: Union[str, object] = values.unset, - ) -> PlaybackGrantInstance: - """ - Asynchronous coroutine to create the PlaybackGrantInstance - - :param ttl: The time to live of the PlaybackGrant. Default value is 15 seconds. Maximum value is 60 seconds. - :param access_control_allow_origin: The full origin URL where the livestream can be streamed. If this is not provided, it can be streamed from any domain. - - :returns: The created PlaybackGrantInstance - """ - data = values.of( - { - "Ttl": ttl, - "AccessControlAllowOrigin": access_control_allow_origin, - } - ) - - payload = await self._version.create_async( - method="POST", uri=self._uri, data=data - ) - - return PlaybackGrantInstance(self._version, payload, sid=self._solution["sid"]) - - def fetch(self) -> PlaybackGrantInstance: - """ - Fetch the PlaybackGrantInstance - - - :returns: The fetched PlaybackGrantInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return PlaybackGrantInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> PlaybackGrantInstance: - """ - Asynchronous coroutine to fetch the PlaybackGrantInstance - - - :returns: The fetched PlaybackGrantInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return PlaybackGrantInstance( - 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 PlaybackGrantList(ListResource): - def __init__(self, version: Version, sid: str): - """ - Initialize the PlaybackGrantList - - :param version: Version that contains the resource - :param sid: The unique string generated to identify the PlayerStreamer resource associated with this PlaybackGrant - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - - def get(self) -> PlaybackGrantContext: - """ - Constructs a PlaybackGrantContext - - """ - return PlaybackGrantContext(self._version, sid=self._solution["sid"]) - - def __call__(self) -> PlaybackGrantContext: - """ - Constructs a PlaybackGrantContext - - """ - return PlaybackGrantContext(self._version, sid=self._solution["sid"]) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/media/MediaBase.py b/twilio/rest/memory/MemoryBase.py similarity index 77% rename from twilio/rest/media/MediaBase.py rename to twilio/rest/memory/MemoryBase.py index 28c5e37a00..1ced0e0da8 100644 --- a/twilio/rest/media/MediaBase.py +++ b/twilio/rest/memory/MemoryBase.py @@ -13,23 +13,24 @@ from twilio.base.domain import Domain from twilio.rest import Client -from twilio.rest.media.v1 import V1 +from twilio.rest.memory.v1 import V1 -class MediaBase(Domain): +class MemoryBase(Domain): + def __init__(self, twilio: Client): """ - Initialize the Media Domain + Initialize the Memory Domain - :returns: Domain for Media + :returns: Domain for Memory """ - super().__init__(twilio, "https://media.twilio.com") + super().__init__(twilio, "https://memory.twilio.com") self._v1: Optional[V1] = None @property def v1(self) -> V1: """ - :returns: Versions v1 of Media + :returns: Versions v1 of Memory """ if self._v1 is None: self._v1 = V1(self) @@ -40,4 +41,4 @@ def __repr__(self) -> str: Provide a friendly representation :returns: Machine friendly representation """ - return "" + return "" 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..9aa8e05f55 --- /dev/null +++ b/twilio/rest/memory/v1/__init__.py @@ -0,0 +1,285 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, 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.event import EventList +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) + return list_instance(store_id) + + 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 events(self, store_id: str, profile_id: str, event_id: str = None): + """ + Access the EventList resource + + :param store_id: The storeId identifier + + :param profile_id: The profileId identifier + + :param event_id: Optional instance ID to directly access EventContext + :returns: EventList instance if event_id is None, otherwise EventContext + """ + list_instance = EventList(self, store_id, profile_id) + if event_id is not None: + return list_instance(event_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) + return list_instance(store_id) + + 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 "" diff --git a/twilio/rest/memory/v1/bulk.py b/twilio/rest/memory/v1/bulk.py new file mode 100644 index 0000000000..4112d066f6 --- /dev/null +++ b/twilio/rest/memory/v1/bulk.py @@ -0,0 +1,327 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, 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_context import InstanceContext +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: Optional[str] = None + ): + 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, + } + + self._context: Optional[BulkContext] = None + + @property + def _proxy(self) -> "BulkContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BulkContext for this BulkInstance + """ + if self._context is None: + self._context = BulkContext( + self._version, + store_id=self._solution["store_id"], + ) + return self._context + + def update( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> "BulkInstance": + """ + Update the BulkInstance + + :param update_profiles_bulk_request: + + :returns: The updated BulkInstance + """ + return self._proxy.update( + update_profiles_bulk_request=update_profiles_bulk_request, + ) + + async def update_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> "BulkInstance": + """ + Asynchronous coroutine to update the BulkInstance + + :param update_profiles_bulk_request: + + :returns: The updated BulkInstance + """ + return await self._proxy.update_async( + update_profiles_bulk_request=update_profiles_bulk_request, + ) + + def update_with_http_info( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> ApiResponse: + """ + Update the BulkInstance with HTTP info + + :param update_profiles_bulk_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.update_with_http_info( + update_profiles_bulk_request=update_profiles_bulk_request, + ) + + async def update_with_http_info_async( + self, update_profiles_bulk_request: UpdateProfilesBulkRequest + ) -> ApiResponse: + """ + Asynchronous coroutine to update the BulkInstance with HTTP info + + :param update_profiles_bulk_request: + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.update_with_http_info_async( + update_profiles_bulk_request=update_profiles_bulk_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 BulkContext(InstanceContext): + + def __init__(self, version: Version, store_id: str): + """ + Initialize the BulkContext + + :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({}) + + 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({}) + + 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: + """ + Asynchronous coroutine to 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: + """ + Asynchronous coroutine to 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 + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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): + """ + Initialize the BulkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, store_id: str) -> BulkContext: + """ + Constructs a BulkContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return BulkContext(self._version, store_id=store_id) + + def __call__(self, store_id: str) -> BulkContext: + """ + Constructs a BulkContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return BulkContext(self._version, store_id=store_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/conversation_summary.py b/twilio/rest/memory/v1/conversation_summary.py new file mode 100644 index 0000000000..adada4fabd --- /dev/null +++ b/twilio/rest/memory/v1/conversation_summary.py @@ -0,0 +1,1295 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, 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 "".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 "".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 "" + + +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, + 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 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[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 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 ConversationSummaryInstance 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 ConversationSummaryInstance 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[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 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[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 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 ConversationSummaryInstance 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 ConversationSummaryInstance 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, + ) -> 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 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, + "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, + 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 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, + "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, + 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 ConversationSummaryPage, 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 = 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, + 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 ConversationSummaryPage, 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 = 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 "" diff --git a/twilio/rest/memory/v1/data_mapping.py b/twilio/rest/memory/v1/data_mapping.py new file mode 100644 index 0000000000..4a055daed3 --- /dev/null +++ b/twilio/rest/memory/v1/data_mapping.py @@ -0,0 +1,1341 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, 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): + 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[DataMappingFromDataSet] = 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 "".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 "".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 "" + + +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.DataMappingFromDataSet] = ( + 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 DataMappingFromDataSet(object): + """ + :ivar type: The source data type, which determines the source of the data and the required configuration parameters. + :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.dataset_id: Optional[str] = payload.get("datasetId") + + def to_dict(self): + return { + "type": self.type, + "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 field_name: The name of the field/column in the source. Deprecated in favor of expression. + :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.field_name: Optional[str] = payload.get("fieldName") + 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 { + "fieldName": self.field_name, + "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 "" diff --git a/twilio/rest/memory/v1/event.py b/twilio/rest/memory/v1/event.py new file mode 100644 index 0000000000..39d17cd57d --- /dev/null +++ b/twilio/rest/memory/v1/event.py @@ -0,0 +1,315 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, 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 EventInstance(InstanceResource): + """ + :ivar message: + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], store_id: str, profile_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 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 "".format(context) + + +class EventList(ListResource): + + class CommunicationLifecycleEventRecipient(object): + """ + :ivar address: The recipient's address. Must be a valid address matching the channel type such as E.164 format for phone numbers. + :ivar participant_id: The unique identifier for the recipient participant. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.address: Optional[str] = payload.get("address") + self.participant_id: Optional[str] = payload.get("participantId") + + def to_dict(self): + return { + "address": self.address, + "participantId": self.participant_id, + } + + class CommunicationLifecycleEventSender(object): + """ + :ivar address: The sender's address. Must be a valid address matching the channel type such as E.164 format for phone numbers. + :ivar participant_id: The unique identifier for the sender participant. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.address: Optional[str] = payload.get("address") + self.participant_id: Optional[str] = payload.get("participantId") + + def to_dict(self): + return { + "address": self.address, + "participantId": self.participant_id, + } + + class ProfileEventRequest(object): + """ + :ivar type: The type of event being sent. + :ivar events: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.type: Optional["EventInstance.str"] = payload.get("type") + self.events: Optional[List[EventList.ProfileEventRequestEvents]] = ( + payload.get("events") + ) + + def to_dict(self): + return { + "type": self.type, + "events": ( + [events.to_dict() for events in self.events] + if self.events is not None + else None + ), + } + + class ProfileEventRequestEvents(object): + """ + :ivar timestamp: The time the event occurred in ISO8601 format with millisecond resolution. Defaults to received time if not provided. + :ivar lifecycle: The lifecycle event type of the communication. + :ivar conversation_id: The unique identifier for the conversation. + :ivar communication_id: The unique identifier for the communication. + :ivar communication_type: The communication channel type. + :ivar communication_status: The lifecycle status of the communication. + :ivar direction: The direction of the communication. + :ivar sender: + :ivar recipient: + :ivar error_code: Error code for FAILED communication status. + :ivar error_message: Error message for FAILED communication status. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.timestamp: Optional[datetime] = payload.get("timestamp") + self.lifecycle: Optional[str] = payload.get("lifecycle") + self.conversation_id: Optional[str] = payload.get("conversationId") + self.communication_id: Optional[str] = payload.get("communicationId") + self.communication_type: Optional[str] = payload.get("communicationType") + self.communication_status: Optional[str] = payload.get( + "communicationStatus" + ) + self.direction: Optional["EventInstance.str"] = payload.get("direction") + self.sender: Optional[EventList.CommunicationLifecycleEventSender] = ( + payload.get("sender") + ) + self.recipient: Optional[EventList.CommunicationLifecycleEventRecipient] = ( + payload.get("recipient") + ) + self.error_code: Optional[str] = payload.get("errorCode") + self.error_message: Optional[str] = payload.get("errorMessage") + + def to_dict(self): + return { + "timestamp": self.timestamp, + "lifecycle": self.lifecycle, + "conversationId": self.conversation_id, + "communicationId": self.communication_id, + "communicationType": self.communication_type, + "communicationStatus": self.communication_status, + "direction": self.direction, + "sender": self.sender.to_dict() if self.sender is not None else None, + "recipient": ( + self.recipient.to_dict() if self.recipient is not None else None + ), + "errorCode": self.error_code, + "errorMessage": self.error_message, + } + + def __init__(self, version: Version, store_id: str, profile_id: str): + """ + Initialize the EventList + + :param version: Version that contains the resource + :param store_id: The storeId identifier + :param profile_id: The profileId identifier + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "store_id": store_id, + "profile_id": profile_id, + } + self._uri = "/Stores/{store_id}/Profiles/{profile_id}/Events".format( + **self._solution + ) + + def _create( + self, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_event_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, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> EventInstance: + """ + Create the EventInstance + + :param profile_event_request: + + :returns: The created EventInstance + """ + payload, _, _ = self._create(profile_event_request=profile_event_request) + return EventInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + def create_with_http_info( + self, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> ApiResponse: + """ + Create the EventInstance and return response metadata + + :param profile_event_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._create( + profile_event_request=profile_event_request + ) + instance = EventInstance( + 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, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> tuple: + """ + Internal async helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = profile_event_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, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> EventInstance: + """ + Asynchronously create the EventInstance + + :param profile_event_request: + + :returns: The created EventInstance + """ + payload, _, _ = await self._create_async( + profile_event_request=profile_event_request + ) + return EventInstance( + self._version, + payload, + store_id=self._solution["store_id"], + profile_id=self._solution["profile_id"], + ) + + async def create_with_http_info_async( + self, profile_event_request: Union[ProfileEventRequest, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the EventInstance and return response metadata + + :param profile_event_request: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._create_async( + profile_event_request=profile_event_request + ) + instance = EventInstance( + 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 "" diff --git a/twilio/rest/memory/v1/identifier.py b/twilio/rest/memory/v1/identifier.py new file mode 100644 index 0000000000..3ac08f718b --- /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, events, 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 "".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 "".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 "" + + +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 "" 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..c575c283b0 --- /dev/null +++ b/twilio/rest/memory/v1/identity_resolution_setting.py @@ -0,0 +1,548 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, 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_context import InstanceContext +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. 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: Optional[str] = None, + ): + 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, + } + + self._context: Optional[IdentityResolutionSettingContext] = None + + @property + def _proxy(self) -> "IdentityResolutionSettingContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: IdentityResolutionSettingContext for this IdentityResolutionSettingInstance + """ + if self._context is None: + self._context = IdentityResolutionSettingContext( + self._version, + store_id=self._solution["store_id"], + ) + return self._context + + def fetch(self) -> "IdentityResolutionSettingInstance": + """ + Fetch the IdentityResolutionSettingInstance + + + :returns: The fetched IdentityResolutionSettingInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "IdentityResolutionSettingInstance": + """ + Asynchronous coroutine to fetch the IdentityResolutionSettingInstance + + + :returns: The fetched IdentityResolutionSettingInstance + """ + return await self._proxy.fetch_async() + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IdentityResolutionSettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return self._proxy.fetch_with_http_info() + + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IdentityResolutionSettingInstance with HTTP info + + + :returns: ApiResponse with instance, status code, and headers + """ + return await self._proxy.fetch_with_http_info_async() + + 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 + """ + return self._proxy.update( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + + async def update_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> "IdentityResolutionSettingInstance": + """ + Asynchronous coroutine to 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 + """ + return await self._proxy.update_async( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + + def update_with_http_info( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Update the IdentityResolutionSettingInstance with HTTP info + + :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 + """ + return self._proxy.update_with_http_info( + identity_resolution_settings_core=identity_resolution_settings_core, + if_match=if_match, + ) + + async def update_with_http_info_async( + self, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to update the IdentityResolutionSettingInstance with HTTP info + + :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 + """ + return await self._proxy.update_with_http_info_async( + identity_resolution_settings_core=identity_resolution_settings_core, + 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 IdentityResolutionSettingContext(InstanceContext): + + def __init__(self, version: Version, store_id: str): + """ + Initialize the IdentityResolutionSettingContext + + :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({}) + + 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({}) + + 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: + """ + Asynchronous coroutine to 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: + """ + Asynchronous coroutine to 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 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, + 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 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, + identity_resolution_settings_core: IdentityResolutionSettingsCore, + if_match: Union[str, object] = values.unset, + ) -> IdentityResolutionSettingInstance: + """ + Asynchronous coroutine to 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: + """ + Asynchronous coroutine to 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 + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".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. 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): + """ + Initialize the IdentityResolutionSettingList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, store_id: str) -> IdentityResolutionSettingContext: + """ + Constructs a IdentityResolutionSettingContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return IdentityResolutionSettingContext(self._version, store_id=store_id) + + def __call__(self, store_id: str) -> IdentityResolutionSettingContext: + """ + Constructs a IdentityResolutionSettingContext + + :param store_id: A unique Memory Store ID using Twilio Type ID (TTID) format + """ + return IdentityResolutionSettingContext(self._version, store_id=store_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/memory/v1/import_.py b/twilio/rest/memory/v1/import_.py new file mode 100644 index 0000000000..73a65e96e1 --- /dev/null +++ b/twilio/rest/memory/v1/import_.py @@ -0,0 +1,738 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, 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 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 imports: + :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 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.imports: Optional[List[str]] = payload.get("imports") + 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.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 "".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 "".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 "" + + +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, + } + + 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 list( + self, + ) -> List[str]: + """ + Lists ImportInstance IDs 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 list(payload["imports"]) + + async def list_async( + self, + ) -> List[str]: + """ + Asynchronously lists ImportInstance IDs 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 list(payload["imports"]) + + def list_with_http_info( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> ApiResponse: + """ + Lists ImportInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, 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 ImportInstance and returns headers from first page + + + :param limit: Upper limit for the number of records to return. list() guarantees + never to return more than limit. Default is no limit + :param page_size: Number of records to fetch per request, when not set will use + the default value of 50 records. If no page_size is defined + but a limit is defined, list() will attempt to read the limit + with the most efficient page size, i.e. 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, + ) -> ImportPage: + """ + Retrieve a single page of ImportInstance records from the API. + Request is executed immediately + + :returns: Page of ImportInstance + """ + 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 ImportPage( + self._version, response, uri=self._uri, params=data, solution=self._solution + ) + + async def page_async( + self, + ) -> ImportPage: + """ + Asynchronously retrieve a single page of ImportInstance records from the API. + Request is executed immediately + + :returns: Page of ImportInstance + """ + 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 ImportPage( + 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 ImportPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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, + page_token: Union[str, object] = values.unset, + 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 ImportPage, status code, and headers + """ + data = values.of( + { + "PageToken": page_token, + "Page": page_number, + "PageSize": page_size, + } + ) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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 "" diff --git a/twilio/rest/memory/v1/lookup.py b/twilio/rest/memory/v1/lookup.py new file mode 100644 index 0000000000..11721acfab --- /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, events, 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 "".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 "" diff --git a/twilio/rest/memory/v1/observation.py b/twilio/rest/memory/v1/observation.py new file mode 100644 index 0000000000..9150a75ef0 --- /dev/null +++ b/twilio/rest/memory/v1/observation.py @@ -0,0 +1,1408 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, 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 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. + :ivar message: + """ + + def __init__( + self, + version: Version, + payload: ResponseResource, + store_id: str, + profile_id: str, + observation_id: Optional[str] = None, + ): + 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") + ) + 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 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_core: ObservationCore) -> "ObservationInstance": + """ + Patch the ObservationInstance + + :param observation_core: + + :returns: The patched ObservationInstance + """ + return self._proxy.patch( + observation_core=observation_core, + ) + + async def patch_async( + self, observation_core: ObservationCore + ) -> "ObservationInstance": + """ + Asynchronous coroutine to patch the ObservationInstance + + :param observation_core: + + :returns: The patched ObservationInstance + """ + return await self._proxy.patch_async( + observation_core=observation_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 "".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_core: ObservationCore) -> tuple: + """ + Internal helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = observation_core.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_core: ObservationCore) -> ObservationInstance: + """ + Patch the ObservationInstance + + :param observation_core: + + :returns: The patched ObservationInstance + """ + payload, _, _ = self._patch(observation_core=observation_core) + 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_core: ObservationCore) -> ApiResponse: + """ + Patch the ObservationInstance and return response metadata + + :param observation_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = self._patch(observation_core=observation_core) + 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_core: ObservationCore) -> tuple: + """ + Internal async helper for patch operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = observation_core.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_core: ObservationCore + ) -> ObservationInstance: + """ + Asynchronous coroutine to patch the ObservationInstance + + :param observation_core: + + :returns: The patched ObservationInstance + """ + payload, _, _ = await self._patch_async(observation_core=observation_core) + 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_core: ObservationCore + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the ObservationInstance and return response metadata + + :param observation_core: + + :returns: ApiResponse with instance, status code, and headers + """ + payload, status_code, headers = await self._patch_async( + observation_core=observation_core + ) + 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 "".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 "" + + +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.ObservationCore]] = ( + 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 ObservationCore(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, + 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 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, + 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, + 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 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, + 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, + 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 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, + 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, + 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 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, + 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, + 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 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, + 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, + 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 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, + 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, + 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 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, + 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, + 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 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, + 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, + 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 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), + "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, + 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 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), + "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, + 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 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), + "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, + 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 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), + "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 "" diff --git a/twilio/rest/memory/v1/operation.py b/twilio/rest/memory/v1/operation.py new file mode 100644 index 0000000000..b8faac294a --- /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, events, 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 "".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 "".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 "" diff --git a/twilio/rest/memory/v1/profile.py b/twilio/rest/memory/v1/profile.py new file mode 100644 index 0000000000..01b1080902 --- /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, events, 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[ProfilesMeta] = 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 "".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 "".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 "" + + +class ProfileList(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 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, + } + + class ProfilesMeta(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, + } + + 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 "" diff --git a/twilio/rest/memory/v1/recall.py b/twilio/rest/memory/v1/recall.py new file mode 100644 index 0000000000..5258e3eb09 --- /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, events, 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 "".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 "" diff --git a/twilio/rest/memory/v1/revision.py b/twilio/rest/memory/v1/revision.py new file mode 100644 index 0000000000..84b8a13a69 --- /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, events, 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 "".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 "" + + +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 "" diff --git a/twilio/rest/memory/v1/store.py b/twilio/rest/memory/v1/store.py new file mode 100644 index 0000000000..c617301a0e --- /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, events, 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 "".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 "".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 "" + + +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: + :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 "" diff --git a/twilio/rest/memory/v1/trait.py b/twilio/rest/memory/v1/trait.py new file mode 100644 index 0000000000..b565d8066c --- /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, events, 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 "".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 "" + + +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 "" diff --git a/twilio/rest/memory/v1/trait_group.py b/twilio/rest/memory/v1/trait_group.py new file mode 100644 index 0000000000..5cf1c5d276 --- /dev/null +++ b/twilio/rest/memory/v1/trait_group.py @@ -0,0 +1,1535 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio Memory API + APIs for managing memory stores, profiles, events, 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, TraitGroupCoreTraitsValue]] = 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 "".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 "".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 "" + + +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: + :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 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.id_type_promotion: Optional[str] = payload.get("idTypePromotion") + + def to_dict(self): + return { + "dataType": self.data_type, + "description": self.description, + "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, TraitGroupCoreTraitsValue]] = 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 TraitGroupCoreTraitsValue(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, TraitGroupCoreTraitsValue]] = 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 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 "" diff --git a/twilio/rest/messaging/MessagingBase.py b/twilio/rest/messaging/MessagingBase.py index ea6b0dd0a5..18b7f3e1a6 100644 --- a/twilio/rest/messaging/MessagingBase.py +++ b/twilio/rest/messaging/MessagingBase.py @@ -14,9 +14,12 @@ 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): + def __init__(self, twilio: Client): """ Initialize the Messaging Domain @@ -25,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: @@ -35,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 159a4422a0..1e1100e32e 100644 --- a/twilio/rest/messaging/v1/__init__.py +++ b/twilio/rest/messaging/v1/__init__.py @@ -22,16 +22,22 @@ 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, ) +from twilio.rest.messaging.v1.linkshortening_messaging_service_domain_association import ( + LinkshorteningMessagingServiceDomainAssociationList, +) +from twilio.rest.messaging.v1.request_managed_cert import RequestManagedCertList from twilio.rest.messaging.v1.service import ServiceList from twilio.rest.messaging.v1.tollfree_verification import TollfreeVerificationList from twilio.rest.messaging.v1.usecase import UsecaseList class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Messaging @@ -46,10 +52,15 @@ 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 ] = None + self._linkshortening_messaging_service_domain_association: Optional[ + LinkshorteningMessagingServiceDomainAssociationList + ] = None + self._request_managed_cert: Optional[RequestManagedCertList] = None self._services: Optional[ServiceList] = None self._tollfree_verifications: Optional[TollfreeVerificationList] = None self._usecases: Optional[UsecaseList] = None @@ -86,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: @@ -100,6 +117,22 @@ def linkshortening_messaging_service(self) -> LinkshorteningMessagingServiceList ) return self._linkshortening_messaging_service + @property + def linkshortening_messaging_service_domain_association( + self, + ) -> LinkshorteningMessagingServiceDomainAssociationList: + if self._linkshortening_messaging_service_domain_association is None: + self._linkshortening_messaging_service_domain_association = ( + LinkshorteningMessagingServiceDomainAssociationList(self) + ) + return self._linkshortening_messaging_service_domain_association + + @property + def request_managed_cert(self) -> RequestManagedCertList: + if self._request_managed_cert is None: + self._request_managed_cert = RequestManagedCertList(self) + return self._request_managed_cert + @property def services(self) -> ServiceList: if self._services is None: diff --git a/twilio/rest/messaging/v1/brand_registration/__init__.py b/twilio/rest/messaging/v1/brand_registration/__init__.py index 68a669e3ce..349d7ba4f3 100644 --- a/twilio/rest/messaging/v1/brand_registration/__init__.py +++ b/twilio/rest/messaging/v1/brand_registration/__init__.py @@ -12,10 +12,10 @@ 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 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 +28,7 @@ class BrandRegistrationInstance(InstanceResource): + class BrandFeedback(object): TAX_ID = "TAX_ID" STOCK_SYMBOL = "STOCK_SYMBOL" @@ -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. @@ -58,10 +61,11 @@ class Status(object): :ivar brand_type: Type of brand. One of: \"STANDARD\", \"SOLE_PROPRIETOR\". SOLE_PROPRIETOR is for the low volume, SOLE_PROPRIETOR campaign use case. There can only be one SOLE_PROPRIETOR campaign created per SOLE_PROPRIETOR brand. STANDARD is for all other campaign use cases. Multiple campaign use cases can be created per STANDARD brand. :ivar status: :ivar tcr_id: Campaign Registry (TCR) Brand ID. Assigned only after successful brand registration. - :ivar failure_reason: A reason why brand registration has failed. Only applicable when status is FAILED. + :ivar failure_reason: DEPRECATED. A reason why brand registration has failed. Only applicable when status is FAILED. + :ivar errors: A list of errors that occurred during the brand registration process. :ivar url: The absolute URL of the Brand Registration resource. :ivar brand_score: The secondary vetting score if it was done. Otherwise, it will be the brand score if it's returned from TCR. It may be null if no score is available. - :ivar brand_feedback: Feedback on how to improve brand score + :ivar brand_feedback: DEPRECATED. Feedback on how to improve brand score :ivar identity_status: :ivar russell_3000: Publicly traded company identified in the Russell 3000 Index :ivar government_entity: Identified as a government entity @@ -96,6 +100,7 @@ def __init__( ) self.tcr_id: Optional[str] = payload.get("tcr_id") self.failure_reason: Optional[str] = payload.get("failure_reason") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") self.url: Optional[str] = payload.get("url") self.brand_score: Optional[int] = deserialize.integer( payload.get("brand_score") @@ -103,9 +108,9 @@ def __init__( self.brand_feedback: Optional[ List["BrandRegistrationInstance.BrandFeedback"] ] = payload.get("brand_feedback") - self.identity_status: Optional[ - "BrandRegistrationInstance.IdentityStatus" - ] = payload.get("identity_status") + self.identity_status: Optional["BrandRegistrationInstance.IdentityStatus"] = ( + payload.get("identity_status") + ) self.russell_3000: Optional[bool] = payload.get("russell_3000") self.government_entity: Optional[bool] = payload.get("government_entity") self.tax_exempt_status: Optional[str] = payload.get("tax_exempt_status") @@ -118,6 +123,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[BrandRegistrationContext] = None @property @@ -153,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 @@ -171,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: """ @@ -196,6 +238,7 @@ def __repr__(self) -> str: class BrandRegistrationContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the BrandRegistrationContext @@ -214,6 +257,22 @@ def __init__(self, version: Version, sid: str): self._brand_registration_otps: Optional[BrandRegistrationOtpList] = None self._brand_vettings: Optional[BrandVettingList] = None + 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) -> BrandRegistrationInstance: """ Fetch the BrandRegistrationInstance @@ -221,17 +280,43 @@ def fetch(self) -> BrandRegistrationInstance: :returns: The fetched BrandRegistrationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return BrandRegistrationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandRegistrationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> BrandRegistrationInstance: """ @@ -240,17 +325,44 @@ async def fetch_async(self) -> BrandRegistrationInstance: :returns: The fetched BrandRegistrationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return BrandRegistrationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return BrandRegistrationInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the BrandRegistrationInstance and return response metadata + + + :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({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def update(self) -> BrandRegistrationInstance: """ @@ -259,17 +371,40 @@ def update(self) -> BrandRegistrationInstance: :returns: The updated BrandRegistrationInstance """ - data = values.of({}) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + payload, _, _ = self._update() + return BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] ) - return BrandRegistrationInstance( + def update_with_http_info(self) -> ApiResponse: + """ + Update the BrandRegistrationInstance and return response metadata + + + :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({}) + headers = values.of({}) + + 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) -> BrandRegistrationInstance: """ @@ -278,17 +413,23 @@ async def update_async(self) -> BrandRegistrationInstance: :returns: The updated BrandRegistrationInstance """ - data = values.of({}) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + payload, _, _ = await self._update_async() + return BrandRegistrationInstance( + self._version, payload, sid=self._solution["sid"] ) - return BrandRegistrationInstance( + 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: @@ -325,12 +466,14 @@ def __repr__(self) -> str: class BrandRegistrationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BrandRegistrationInstance: """ Build an instance of BrandRegistrationInstance :param payload: Payload response from the API """ + return BrandRegistrationInstance(self._version, payload) def __repr__(self) -> str: @@ -343,6 +486,7 @@ def __repr__(self) -> str: class BrandRegistrationList(ListResource): + def __init__(self, version: Version): """ Initialize the BrandRegistrationList @@ -354,6 +498,42 @@ def __init__(self, version: Version): self._uri = "/a2p/BrandRegistrations" + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "CustomerProfileBundleSid": customer_profile_bundle_sid, + "A2PProfileBundleSid": a2p_profile_bundle_sid, + "BrandType": brand_type, + "Mock": serialize.boolean_to_string(mock), + "SkipAutomaticSecVet": serialize.boolean_to_string( + skip_automatic_sec_vet + ), + } + ) + 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, customer_profile_bundle_sid: str, @@ -373,23 +553,79 @@ def create( :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( { "CustomerProfileBundleSid": customer_profile_bundle_sid, "A2PProfileBundleSid": a2p_profile_bundle_sid, "BrandType": brand_type, - "Mock": mock, - "SkipAutomaticSecVet": skip_automatic_sec_vet, + "Mock": serialize.boolean_to_string(mock), + "SkipAutomaticSecVet": serialize.boolean_to_string( + skip_automatic_sec_vet + ), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return BrandRegistrationInstance(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, @@ -410,23 +646,43 @@ async def create_async( :returns: The created BrandRegistrationInstance """ - data = values.of( - { - "CustomerProfileBundleSid": customer_profile_bundle_sid, - "A2PProfileBundleSid": a2p_profile_bundle_sid, - "BrandType": brand_type, - "Mock": mock, - "SkipAutomaticSecVet": skip_automatic_sec_vet, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return BrandRegistrationInstance(self._version, payload) + :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, @@ -478,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, @@ -497,6 +803,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -523,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( @@ -531,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, @@ -555,7 +913,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 BrandRegistrationPage(self._version, response) async def page_async( @@ -582,11 +946,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 3cc7d364bb..0ac2f302c5 100644 --- a/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py +++ b/twilio/rest/messaging/v1/brand_registration/brand_registration_otp.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class BrandRegistrationOtpInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Brand Registration resource. :ivar brand_registration_sid: The unique string to identify Brand Registration of Sole Proprietor Brand @@ -52,6 +52,7 @@ def __repr__(self) -> str: class BrandRegistrationOtpList(ListResource): + def __init__(self, version: Version, brand_registration_sid: str): """ Initialize the BrandRegistrationOtpList @@ -70,6 +71,22 @@ def __init__(self, version: Version, brand_registration_sid: str): **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) -> BrandRegistrationOtpInstance: """ Create the BrandRegistrationOtpInstance @@ -77,17 +94,43 @@ def create(self) -> BrandRegistrationOtpInstance: :returns: The created BrandRegistrationOtpInstance """ - - payload = self._version.create( - method="POST", - uri=self._uri, + payload, _, _ = self._create() + return BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], ) - return BrandRegistrationOtpInstance( + def create_with_http_info(self) -> ApiResponse: + """ + Create the BrandRegistrationOtpInstance and return response metadata + + + :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) async def create_async(self) -> BrandRegistrationOtpInstance: """ @@ -96,17 +139,27 @@ async def create_async(self) -> BrandRegistrationOtpInstance: :returns: The created BrandRegistrationOtpInstance """ - - payload = await self._version.create_async( - method="POST", - uri=self._uri, + payload, _, _ = await self._create_async() + return BrandRegistrationOtpInstance( + self._version, + payload, + brand_registration_sid=self._solution["brand_registration_sid"], ) - return BrandRegistrationOtpInstance( + 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: """ diff --git a/twilio/rest/messaging/v1/brand_registration/brand_vetting.py b/twilio/rest/messaging/v1/brand_registration/brand_vetting.py index 2fff9ebbed..9cd9243470 100644 --- a/twilio/rest/messaging/v1/brand_registration/brand_vetting.py +++ b/twilio/rest/messaging/v1/brand_registration/brand_vetting.py @@ -12,10 +12,10 @@ 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 @@ -24,8 +24,10 @@ 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. @@ -61,15 +63,16 @@ def __init__( self.vetting_id: Optional[str] = payload.get("vetting_id") self.vetting_class: Optional[str] = payload.get("vetting_class") self.vetting_status: Optional[str] = payload.get("vetting_status") - self.vetting_provider: Optional[ - "BrandVettingInstance.VettingProvider" - ] = payload.get("vetting_provider") + self.vetting_provider: Optional["BrandVettingInstance.VettingProvider"] = ( + payload.get("vetting_provider") + ) self.url: Optional[str] = payload.get("url") self._solution = { "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 @@ -117,6 +138,7 @@ def __repr__(self) -> str: class BrandVettingContext(InstanceContext): + def __init__(self, version: Version, brand_sid: str, brand_vetting_sid: str): """ Initialize the BrandVettingContext @@ -138,6 +160,22 @@ def __init__(self, version: Version, brand_sid: str, brand_vetting_sid: str): ) ) + 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) -> BrandVettingInstance: """ Fetch the BrandVettingInstance @@ -145,18 +183,45 @@ def fetch(self) -> BrandVettingInstance: :returns: The fetched BrandVettingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], ) - return BrandVettingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BrandVettingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> BrandVettingInstance: """ @@ -165,18 +230,29 @@ async def fetch_async(self) -> BrandVettingInstance: :returns: The fetched BrandVettingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return BrandVettingInstance( + self._version, + payload, + brand_sid=self._solution["brand_sid"], + brand_vetting_sid=self._solution["brand_vetting_sid"], ) - return BrandVettingInstance( + 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: """ @@ -189,12 +265,14 @@ def __repr__(self) -> str: class BrandVettingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BrandVettingInstance: """ Build an instance of BrandVettingInstance :param payload: Payload response from the API """ + return BrandVettingInstance( self._version, payload, brand_sid=self._solution["brand_sid"] ) @@ -209,6 +287,7 @@ def __repr__(self) -> str: class BrandVettingList(ListResource): + def __init__(self, version: Version, brand_sid: str): """ Initialize the BrandVettingList @@ -227,6 +306,34 @@ def __init__(self, version: Version, brand_sid: str): **self._solution ) + def _create( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "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 self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, vetting_provider: "BrandVettingInstance.VettingProvider", @@ -240,21 +347,60 @@ def create( :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"] + ) + + def create_with_http_info( + self, + vetting_provider: "BrandVettingInstance.VettingProvider", + vetting_id: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + 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 = 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( { "VettingProvider": vetting_provider, "VettingId": vetting_id, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return BrandVettingInstance( - self._version, payload, brand_sid=self._solution["brand_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( @@ -270,22 +416,33 @@ async def create_async( :returns: The created BrandVettingInstance """ - data = values.of( - { - "VettingProvider": vetting_provider, - "VettingId": vetting_id, - } + payload, _, _ = await self._create_async( + vetting_provider=vetting_provider, vetting_id=vetting_id ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return BrandVettingInstance( + self._version, payload, brand_sid=self._solution["brand_sid"] ) - return BrandVettingInstance( + 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, @@ -349,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[ @@ -372,6 +589,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( vetting_provider=vetting_provider, @@ -403,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( @@ -412,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[ @@ -441,8 +720,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return BrandVettingPage(self._version, response, self._solution) + 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 BrandVettingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -473,10 +758,94 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return BrandVettingPage(self._version, response, self._solution) + 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: """ @@ -488,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: """ @@ -500,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 972ee62e30..ddcbff4af8 100644 --- a/twilio/rest/messaging/v1/deactivations.py +++ b/twilio/rest/messaging/v1/deactivations.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,7 +23,6 @@ class DeactivationsInstance(InstanceResource): - """ :ivar redirect_to: Returns an authenticated url that redirects to a file containing the deactivated numbers for the requested day. This url is valid for up to two minutes. """ @@ -77,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 @@ -88,6 +115,7 @@ def __repr__(self) -> str: class DeactivationsContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the DeactivationsContext @@ -98,54 +126,114 @@ 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), } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, 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), } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, 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 @@ -157,6 +245,7 @@ def __repr__(self) -> str: class DeactivationsList(ListResource): + def __init__(self, version: Version): """ Initialize the DeactivationsList diff --git a/twilio/rest/messaging/v1/domain_certs.py b/twilio/rest/messaging/v1/domain_certs.py index 71ef3105bc..76fea05f18 100644 --- a/twilio/rest/messaging/v1/domain_certs.py +++ b/twilio/rest/messaging/v1/domain_certs.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ 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. @@ -63,6 +62,7 @@ def __init__( self._solution = { "domain_sid": domain_sid or self.domain_sid, } + self._context: Optional[DomainCertsContext] = None @property @@ -98,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 @@ -116,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 @@ -140,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 @@ -151,6 +211,7 @@ def __repr__(self) -> str: class DomainCertsContext(InstanceContext): + def __init__(self, version: Version, domain_sid: str): """ Initialize the DomainCertsContext @@ -168,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 @@ -175,9 +250,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -187,9 +284,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DomainCertsInstance 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) -> DomainCertsInstance: @@ -199,17 +320,43 @@ def fetch(self) -> DomainCertsInstance: :returns: The fetched DomainCertsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return DomainCertsInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], ) - return DomainCertsInstance( + 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: """ @@ -218,66 +365,128 @@ async def fetch_async(self) -> DomainCertsInstance: :returns: The fetched DomainCertsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + 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( { "TlsCert": tls_cert, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, 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( { "TlsCert": tls_cert, } ) + 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, + 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 @@ -289,6 +498,7 @@ def __repr__(self) -> str: class DomainCertsList(ListResource): + def __init__(self, version: Version): """ Initialize the DomainCertsList diff --git a/twilio/rest/messaging/v1/domain_config.py b/twilio/rest/messaging/v1/domain_config.py index af4d28771e..1fa8341f21 100644 --- a/twilio/rest/messaging/v1/domain_config.py +++ b/twilio/rest/messaging/v1/domain_config.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - from datetime import datetime -from typing import Any, Dict, List, Optional, Union +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 @@ -23,16 +23,16 @@ class DomainConfigInstance(InstanceResource): - """ :ivar domain_sid: The unique string that we created to identify the Domain resource. :ivar config_sid: The unique string that we created to identify the Domain config (prefix ZK). - :ivar messaging_service_sids: A list of messagingServiceSids (with prefix MG). :ivar 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. :ivar callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links. + :ivar continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service :ivar date_created: Date this Domain Config was created. :ivar date_updated: Date that this Domain Config was last updated. :ivar url: + :ivar 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. """ def __init__( @@ -45,11 +45,9 @@ def __init__( self.domain_sid: Optional[str] = payload.get("domain_sid") self.config_sid: Optional[str] = payload.get("config_sid") - self.messaging_service_sids: Optional[List[str]] = payload.get( - "messaging_service_sids" - ) self.fallback_url: Optional[str] = payload.get("fallback_url") self.callback_url: Optional[str] = payload.get("callback_url") + self.continue_on_failure: Optional[bool] = payload.get("continue_on_failure") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -57,10 +55,12 @@ def __init__( payload.get("date_updated") ) self.url: Optional[str] = payload.get("url") + self.disable_https: Optional[bool] = payload.get("disable_https") self._solution = { "domain_sid": domain_sid or self.domain_sid, } + self._context: Optional[DomainConfigContext] = None @property @@ -96,52 +96,118 @@ 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, - messaging_service_sids: List[str], fallback_url: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, - messaging_service_sids_action: 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 messaging_service_sids: A list of messagingServiceSids (with prefix MG) :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 messaging_service_sids_action: An action type for messaging_service_sids operation (ADD, DELETE, REPLACE) + :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 """ return self._proxy.update( - messaging_service_sids=messaging_service_sids, fallback_url=fallback_url, callback_url=callback_url, - messaging_service_sids_action=messaging_service_sids_action, + continue_on_failure=continue_on_failure, + disable_https=disable_https, ) async def update_async( self, - messaging_service_sids: List[str], fallback_url: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, - messaging_service_sids_action: 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 messaging_service_sids: A list of messagingServiceSids (with prefix MG) :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 messaging_service_sids_action: An action type for messaging_service_sids operation (ADD, DELETE, REPLACE) + :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 """ return await self._proxy.update_async( - messaging_service_sids=messaging_service_sids, fallback_url=fallback_url, callback_url=callback_url, - messaging_service_sids_action=messaging_service_sids_action, + continue_on_failure=continue_on_failure, + 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: @@ -155,6 +221,7 @@ def __repr__(self) -> str: class DomainConfigContext(InstanceContext): + def __init__(self, version: Version, domain_sid: str): """ Initialize the DomainConfigContext @@ -172,6 +239,22 @@ def __init__(self, version: Version, domain_sid: str): **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) -> DomainConfigInstance: """ Fetch the DomainConfigInstance @@ -179,17 +262,43 @@ def fetch(self) -> DomainConfigInstance: :returns: The fetched DomainConfigInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], ) - return DomainConfigInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> DomainConfigInstance: """ @@ -198,93 +307,201 @@ async def fetch_async(self) -> DomainConfigInstance: :returns: The fetched DomainConfigInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return DomainConfigInstance( + self._version, + payload, + domain_sid=self._solution["domain_sid"], ) - return DomainConfigInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FallbackUrl": fallback_url, + "CallbackUrl": callback_url, + "ContinueOnFailure": serialize.boolean_to_string(continue_on_failure), + "DisableHttps": serialize.boolean_to_string(disable_https), + } + ) + 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, - messaging_service_sids: List[str], fallback_url: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, - messaging_service_sids_action: 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 messaging_service_sids: A list of messagingServiceSids (with prefix MG) :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 messaging_service_sids_action: An action type for messaging_service_sids operation (ADD, DELETE, REPLACE) + :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"] + ) + + 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 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 = 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( { - "MessagingServiceSids": serialize.map( - messaging_service_sids, lambda e: e - ), "FallbackUrl": fallback_url, "CallbackUrl": callback_url, - "MessagingServiceSidsAction": messaging_service_sids_action, + "ContinueOnFailure": serialize.boolean_to_string(continue_on_failure), + "DisableHttps": serialize.boolean_to_string(disable_https), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return DomainConfigInstance( - self._version, payload, domain_sid=self._solution["domain_sid"] + 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_service_sids: List[str], fallback_url: Union[str, object] = values.unset, callback_url: Union[str, object] = values.unset, - messaging_service_sids_action: 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 messaging_service_sids: A list of messagingServiceSids (with prefix MG) :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 messaging_service_sids_action: An action type for messaging_service_sids operation (ADD, DELETE, REPLACE) + :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 """ - data = values.of( - { - "MessagingServiceSids": serialize.map( - messaging_service_sids, lambda e: e - ), - "FallbackUrl": fallback_url, - "CallbackUrl": callback_url, - "MessagingServiceSidsAction": messaging_service_sids_action, - } + payload, _, _ = await self._update_async( + fallback_url=fallback_url, + callback_url=callback_url, + continue_on_failure=continue_on_failure, + disable_https=disable_https, ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return DomainConfigInstance( + self._version, payload, domain_sid=self._solution["domain_sid"] ) - return DomainConfigInstance( + 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: """ @@ -297,6 +514,7 @@ def __repr__(self) -> str: class DomainConfigList(ListResource): + def __init__(self, version: Version): """ Initialize the DomainConfigList diff --git a/twilio/rest/messaging/v1/domain_config_messaging_service.py b/twilio/rest/messaging/v1/domain_config_messaging_service.py index 6e5866900b..b8291f2585 100644 --- a/twilio/rest/messaging/v1/domain_config_messaging_service.py +++ b/twilio/rest/messaging/v1/domain_config_messaging_service.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - from datetime import datetime from typing import Any, Dict, Optional -from twilio.base import deserialize +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,13 +23,13 @@ class DomainConfigMessagingServiceInstance(InstanceResource): - """ :ivar domain_sid: The unique string that we created to identify the Domain resource. :ivar config_sid: The unique string that we created to identify the Domain config (prefix ZK). :ivar messaging_service_sid: The unique string that identifies the messaging service :ivar 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. :ivar callback_url: URL to receive click events to your webhook whenever the recipients click on the shortened links. + :ivar continue_on_failure: Boolean field to set customer delivery preference when there is a failure in linkShortening service :ivar date_created: Date this Domain Config was created. :ivar date_updated: Date that this Domain Config was last updated. :ivar url: @@ -48,6 +48,7 @@ def __init__( self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") self.fallback_url: Optional[str] = payload.get("fallback_url") self.callback_url: Optional[str] = payload.get("callback_url") + self.continue_on_failure: Optional[bool] = payload.get("continue_on_failure") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -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 @@ -108,6 +128,7 @@ def __repr__(self) -> str: class DomainConfigMessagingServiceContext(InstanceContext): + def __init__(self, version: Version, messaging_service_sid: str): """ Initialize the DomainConfigMessagingServiceContext @@ -125,6 +146,22 @@ def __init__(self, version: Version, messaging_service_sid: str): **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) -> DomainConfigMessagingServiceInstance: """ Fetch the DomainConfigMessagingServiceInstance @@ -132,17 +169,43 @@ def fetch(self) -> DomainConfigMessagingServiceInstance: :returns: The fetched DomainConfigMessagingServiceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], ) - return DomainConfigMessagingServiceInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DomainConfigMessagingServiceInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> DomainConfigMessagingServiceInstance: """ @@ -151,17 +214,27 @@ async def fetch_async(self) -> DomainConfigMessagingServiceInstance: :returns: The fetched DomainConfigMessagingServiceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return DomainConfigMessagingServiceInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], ) - return DomainConfigMessagingServiceInstance( + 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: """ @@ -176,6 +249,7 @@ def __repr__(self) -> str: class DomainConfigMessagingServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the DomainConfigMessagingServiceList 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 "".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 "".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 "" diff --git a/twilio/rest/messaging/v1/external_campaign.py b/twilio/rest/messaging/v1/external_campaign.py index dd1890644b..dd16e80319 100644 --- a/twilio/rest/messaging/v1/external_campaign.py +++ b/twilio/rest/messaging/v1/external_campaign.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,12 +23,11 @@ class ExternalCampaignInstance(InstanceResource): - """ :ivar sid: The unique string that identifies a US A2P Compliance resource `QE2c6890da8086d771620e9b13fadeba0b`. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Campaign belongs to. :ivar campaign_id: ID of the preregistered campaign. - :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services/api) that the resource is associated with. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that 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. """ @@ -54,6 +53,7 @@ def __repr__(self) -> str: class ExternalCampaignList(ListResource): + def __init__(self, version: Version): """ Initialize the ExternalCampaignList @@ -65,57 +65,155 @@ def __init__(self, version: Version): self._uri = "/Services/PreregisteredUsa2p" + def _create( + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "CampaignId": campaign_id, + "MessagingServiceSid": messaging_service_sid, + "CnpMigration": serialize.boolean_to_string(cnp_migration), + } + ) + 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, campaign_id: str, messaging_service_sid: str + self, + campaign_id: str, + messaging_service_sid: str, + cnp_migration: Union[bool, object] = values.unset, ) -> 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/services/api) that the resource is associated with. + :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, _, _ = 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( { "CampaignId": campaign_id, "MessagingServiceSid": messaging_service_sid, + "CnpMigration": serialize.boolean_to_string(cnp_migration), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ExternalCampaignInstance(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, campaign_id: str, messaging_service_sid: str + 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/services/api) that the resource is associated with. + :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 """ - data = values.of( - { - "CampaignId": campaign_id, - "MessagingServiceSid": messaging_service_sid, - } + payload, _, _ = await self._create_async( + campaign_id=campaign_id, + messaging_service_sid=messaging_service_sid, + cnp_migration=cnp_migration, ) + return ExternalCampaignInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return ExternalCampaignInstance(self._version, payload) + :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: """ diff --git a/twilio/rest/messaging/v1/linkshortening_messaging_service.py b/twilio/rest/messaging/v1/linkshortening_messaging_service.py index c5b20e28a5..9549b84828 100644 --- a/twilio/rest/messaging/v1/linkshortening_messaging_service.py +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service.py @@ -12,9 +12,9 @@ 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 @@ -22,7 +22,6 @@ class LinkshorteningMessagingServiceInstance(InstanceResource): - """ :ivar domain_sid: The unique string identifies the domain resource :ivar messaging_service_sid: The unique string that identifies the messaging service @@ -47,6 +46,7 @@ def __init__( "messaging_service_sid": messaging_service_sid or self.messaging_service_sid, } + self._context: Optional[LinkshorteningMessagingServiceContext] = None @property @@ -83,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 @@ -101,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 @@ -114,6 +150,7 @@ def __repr__(self) -> str: class LinkshorteningMessagingServiceContext(InstanceContext): + def __init__(self, version: Version, domain_sid: str, messaging_service_sid: str): """ Initialize the LinkshorteningMessagingServiceContext @@ -133,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 @@ -140,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: """ @@ -158,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: """ @@ -178,9 +287,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -190,10 +321,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the LinkshorteningMessagingServiceInstance 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 __repr__(self) -> str: """ @@ -208,6 +347,7 @@ def __repr__(self) -> str: class LinkshorteningMessagingServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the LinkshorteningMessagingServiceList diff --git a/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py b/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.py new file mode 100644 index 0000000000..1d88d07d0f --- /dev/null +++ b/twilio/rest/messaging/v1/linkshortening_messaging_service_domain_association.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 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 LinkshorteningMessagingServiceDomainAssociationInstance(InstanceResource): + """ + :ivar domain_sid: The unique string that we created to identify the Domain resource. + :ivar messaging_service_sid: The unique string that identifies the messaging service + :ivar url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: Optional[str] = None, + ): + super().__init__(version) + + self.domain_sid: Optional[str] = payload.get("domain_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "messaging_service_sid": messaging_service_sid + or self.messaging_service_sid, + } + + self._context: Optional[ + LinkshorteningMessagingServiceDomainAssociationContext + ] = None + + @property + def _proxy(self) -> "LinkshorteningMessagingServiceDomainAssociationContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: LinkshorteningMessagingServiceDomainAssociationContext for this LinkshorteningMessagingServiceDomainAssociationInstance + """ + if self._context is None: + self._context = LinkshorteningMessagingServiceDomainAssociationContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + return self._context + + def fetch(self) -> "LinkshorteningMessagingServiceDomainAssociationInstance": + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + return self._proxy.fetch() + + async def fetch_async( + self, + ) -> "LinkshorteningMessagingServiceDomainAssociationInstance": + """ + Asynchronous coroutine to fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class LinkshorteningMessagingServiceDomainAssociationContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the LinkshorteningMessagingServiceDomainAssociationContext + + :param version: Version that contains the resource + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = ( + "/LinkShortening/MessagingServices/{messaging_service_sid}/Domain".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) -> LinkshorteningMessagingServiceDomainAssociationInstance: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance + + + :returns: The fetched LinkshorteningMessagingServiceDomainAssociationInstance + """ + payload, _, _ = self._fetch() + return LinkshorteningMessagingServiceDomainAssociationInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LinkshorteningMessagingServiceDomainAssociationInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class LinkshorteningMessagingServiceDomainAssociationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the LinkshorteningMessagingServiceDomainAssociationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceDomainAssociationContext: + """ + Constructs a LinkshorteningMessagingServiceDomainAssociationContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return LinkshorteningMessagingServiceDomainAssociationContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __call__( + self, messaging_service_sid: str + ) -> LinkshorteningMessagingServiceDomainAssociationContext: + """ + Constructs a LinkshorteningMessagingServiceDomainAssociationContext + + :param messaging_service_sid: Unique string used to identify the Messaging service that this domain should be associated with. + """ + return LinkshorteningMessagingServiceDomainAssociationContext( + self._version, messaging_service_sid=messaging_service_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return ( + "" + ) diff --git a/twilio/rest/messaging/v1/request_managed_cert.py b/twilio/rest/messaging/v1/request_managed_cert.py new file mode 100644 index 0000000000..227e36af9c --- /dev/null +++ b/twilio/rest/messaging/v1/request_managed_cert.py @@ -0,0 +1,275 @@ +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 RequestManagedCertInstance(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_created: Date that this Domain was registered to the Twilio platform to create a new Domain object. + :ivar date_expires: Date that the private certificate associated with this domain expires. This is the expiration date of your existing cert. + :ivar domain_name: Full url path for this domain. + :ivar certificate_sid: The unique string that we created to identify this Certificate resource. + :ivar url: + :ivar managed: A boolean flag indicating if the certificate is managed by Twilio. + :ivar requesting: A boolean flag indicating if a managed certificate needs to be fulfilled by Twilio. + """ + + 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_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_expires: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_expires") + ) + self.domain_name: Optional[str] = payload.get("domain_name") + self.certificate_sid: Optional[str] = payload.get("certificate_sid") + self.url: Optional[str] = payload.get("url") + self.managed: Optional[bool] = payload.get("managed") + self.requesting: Optional[bool] = payload.get("requesting") + + self._solution = { + "domain_sid": domain_sid or self.domain_sid, + } + + self._context: Optional[RequestManagedCertContext] = None + + @property + def _proxy(self) -> "RequestManagedCertContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RequestManagedCertContext for this RequestManagedCertInstance + """ + if self._context is None: + self._context = RequestManagedCertContext( + self._version, + domain_sid=self._solution["domain_sid"], + ) + return self._context + + def update(self) -> "RequestManagedCertInstance": + """ + Update the RequestManagedCertInstance + + + :returns: The updated RequestManagedCertInstance + """ + return self._proxy.update() + + async def update_async(self) -> "RequestManagedCertInstance": + """ + Asynchronous coroutine to update the RequestManagedCertInstance + + + :returns: The updated 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RequestManagedCertContext(InstanceContext): + + def __init__(self, version: Version, domain_sid: str): + """ + Initialize the RequestManagedCertContext + + :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}/RequestManagedCert".format( + **self._solution + ) + + def _update(self) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + 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"] + ) + + def update_with_http_info(self) -> ApiResponse: + """ + Update the RequestManagedCertInstance and return response metadata + + + :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({}) + headers = values.of({}) + + 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) -> 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class RequestManagedCertList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the RequestManagedCertList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, domain_sid: str) -> RequestManagedCertContext: + """ + Constructs a RequestManagedCertContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return RequestManagedCertContext(self._version, domain_sid=domain_sid) + + def __call__(self, domain_sid: str) -> RequestManagedCertContext: + """ + Constructs a RequestManagedCertContext + + :param domain_sid: Unique string used to identify the domain that this certificate should be associated with. + """ + return RequestManagedCertContext(self._version, domain_sid=domain_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/messaging/v1/service/__init__.py b/twilio/rest/messaging/v1/service/__init__.py index 73ee02bb33..d7da850830 100644 --- a/twilio/rest/messaging/v1/service/__init__.py +++ b/twilio/rest/messaging/v1/service/__init__.py @@ -12,16 +12,20 @@ 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 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.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 @@ -31,6 +35,7 @@ class ServiceInstance(InstanceResource): + class ScanMessageContent(object): INHERIT = "inherit" ENABLE = "enable" @@ -47,17 +52,17 @@ class ScanMessageContent(object): :ivar 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. :ivar fallback_method: The HTTP method we use to call `fallback_url`. Can be: `GET` or `POST`. :ivar status_callback: The URL we call to [pass status updates](https://www.twilio.com/docs/sms/api/message-resource#message-status-values) about message delivery. - :ivar sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/sms/services#sticky-sender) on the Service instance. - :ivar mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/sms/services#mms-converter) for messages sent through the Service instance. - :ivar smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/sms/services#smart-encoding) for messages sent through the Service instance. + :ivar sticky_sender: Whether to enable [Sticky Sender](https://www.twilio.com/docs/messaging/services#sticky-sender) on the Service instance. + :ivar mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/messaging/services#mms-converter) for messages sent through the Service instance. + :ivar smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/messaging/services#smart-encoding) for messages sent through the Service instance. :ivar scan_message_content: - :ivar fallback_to_long_code: Whether to enable [Fallback to Long Code](https://www.twilio.com/docs/sms/services#fallback-to-long-code) for messages sent through the Service instance. - :ivar area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/sms/services#area-code-geomatch) on the Service Instance. + :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`. + :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. Examples: [notification, marketing, verification, poll ..] + :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`. :ivar us_app_to_person_registered: Whether US A2P campaign is registered for this Service. :ivar 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. """ @@ -84,9 +89,9 @@ def __init__( self.sticky_sender: Optional[bool] = payload.get("sticky_sender") self.mms_converter: Optional[bool] = payload.get("mms_converter") self.smart_encoding: Optional[bool] = payload.get("smart_encoding") - self.scan_message_content: Optional[ - "ServiceInstance.ScanMessageContent" - ] = payload.get("scan_message_content") + self.scan_message_content: Optional["ServiceInstance.ScanMessageContent"] = ( + payload.get("scan_message_content") + ) self.fallback_to_long_code: Optional[bool] = payload.get( "fallback_to_long_code" ) @@ -110,6 +115,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -145,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 @@ -163,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, @@ -193,15 +235,15 @@ def update( :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/sms/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/sms/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/sms/services#smart-encoding) for messages sent through the Service instance. + :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: Whether to enable [Fallback to Long Code](https://www.twilio.com/docs/sms/services#fallback-to-long-code) for messages sent through the Service instance. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/sms/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`. + :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. Examples: [notification, marketing, verification, poll ..] + :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 @@ -255,15 +297,15 @@ async def update_async( :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/sms/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/sms/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/sms/services#smart-encoding) for messages sent through the Service instance. + :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: Whether to enable [Fallback to Long Code](https://www.twilio.com/docs/sms/services#fallback-to-long-code) for messages sent through the Service instance. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/sms/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`. + :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. Examples: [notification, marketing, verification, poll ..] + :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 @@ -287,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: """ @@ -294,6 +460,20 @@ def alpha_senders(self) -> AlphaSenderList: """ return self._proxy.alpha_senders + @property + def channel_senders(self) -> ChannelSenderList: + """ + Access the channel_senders + """ + 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: """ @@ -333,6 +513,7 @@ def __repr__(self) -> str: class ServiceContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ServiceContext @@ -349,11 +530,27 @@ def __init__(self, version: Version, sid: str): self._uri = "/Services/{sid}".format(**self._solution) 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 @@ -361,9 +558,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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: @@ -373,9 +592,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -385,17 +628,43 @@ def fetch(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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: """ @@ -404,19 +673,29 @@ async def fetch_async(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, inbound_request_url: Union[str, object] = values.unset, @@ -436,29 +715,14 @@ 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/sms/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/sms/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/sms/services#smart-encoding) for messages sent through the Service instance. - :param scan_message_content: - :param fallback_to_long_code: Whether to enable [Fallback to Long Code](https://www.twilio.com/docs/sms/services#fallback-to-long-code) for messages sent through the Service instance. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/sms/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`. - :param synchronous_validation: Reserved. - :param usecase: A string that describes the scenario in which the Messaging Service will be used. Examples: [notification, marketing, verification, poll ..] - :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( { "FriendlyName": friendly_name, @@ -467,28 +731,35 @@ def update( "FallbackUrl": fallback_url, "FallbackMethod": fallback_method, "StatusCallback": status_callback, - "StickySender": sticky_sender, - "MmsConverter": mms_converter, - "SmartEncoding": smart_encoding, + "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": fallback_to_long_code, - "AreaCodeGeomatch": area_code_geomatch, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), "ValidityPeriod": validity_period, - "SynchronousValidation": synchronous_validation, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), "Usecase": usecase, - "UseInboundWebhookOnNumber": use_inbound_webhook_on_number, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - async def update_async( + 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, inbound_request_url: Union[str, object] = values.unset, @@ -510,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. @@ -518,60 +789,330 @@ async def update_async( :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/sms/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/sms/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/sms/services#smart-encoding) for messages sent through the Service instance. + :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: Whether to enable [Fallback to Long Code](https://www.twilio.com/docs/sms/services#fallback-to-long-code) for messages sent through the Service instance. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/sms/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`. + :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. Examples: [notification, marketing, verification, poll ..] + :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 """ - data = values.of( - { - "FriendlyName": friendly_name, - "InboundRequestUrl": inbound_request_url, - "InboundMethod": inbound_method, - "FallbackUrl": fallback_url, - "FallbackMethod": fallback_method, - "StatusCallback": status_callback, - "StickySender": sticky_sender, - "MmsConverter": mms_converter, - "SmartEncoding": smart_encoding, - "ScanMessageContent": scan_message_content, - "FallbackToLongCode": fallback_to_long_code, - "AreaCodeGeomatch": area_code_geomatch, - "ValidityPeriod": validity_period, - "SynchronousValidation": synchronous_validation, - "Usecase": usecase, - "UseInboundWebhookOnNumber": use_inbound_webhook_on_number, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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"]) - @property - def alpha_senders(self) -> AlphaSenderList: - """ - Access the alpha_senders - """ - if self._alpha_senders is None: - self._alpha_senders = AlphaSenderList( - self._version, - self._solution["sid"], - ) + 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( + 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({}) + + 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, + 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: + """ + Access the alpha_senders + """ + if self._alpha_senders is None: + self._alpha_senders = AlphaSenderList( + self._version, + self._solution["sid"], + ) return self._alpha_senders + @property + def channel_senders(self) -> ChannelSenderList: + """ + Access the channel_senders + """ + if self._channel_senders is None: + self._channel_senders = ChannelSenderList( + self._version, + self._solution["sid"], + ) + 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: """ @@ -631,12 +1172,14 @@ def __repr__(self) -> str: 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: @@ -649,6 +1192,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -660,7 +1204,134 @@ 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, @@ -680,9 +1351,9 @@ 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: + ) -> ApiResponse: """ - 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. :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. @@ -690,19 +1361,68 @@ def create( :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/sms/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/sms/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/sms/services#smart-encoding) for messages sent through the Service instance. + :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: Whether to enable [Fallback to Long Code](https://www.twilio.com/docs/sms/services#fallback-to-long-code) for messages sent through the Service instance. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/sms/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`. + :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. Examples: [notification, marketing, verification, poll ..]. + :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 + :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, + 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 create operation + + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -711,26 +1431,33 @@ def create( "FallbackUrl": fallback_url, "FallbackMethod": fallback_method, "StatusCallback": status_callback, - "StickySender": sticky_sender, - "MmsConverter": mms_converter, - "SmartEncoding": smart_encoding, + "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": fallback_to_long_code, - "AreaCodeGeomatch": area_code_geomatch, + "FallbackToLongCode": serialize.boolean_to_string( + fallback_to_long_code + ), + "AreaCodeGeomatch": serialize.boolean_to_string(area_code_geomatch), "ValidityPeriod": validity_period, - "SynchronousValidation": synchronous_validation, + "SynchronousValidation": serialize.boolean_to_string( + synchronous_validation + ), "Usecase": usecase, - "UseInboundWebhookOnNumber": use_inbound_webhook_on_number, + "UseInboundWebhookOnNumber": serialize.boolean_to_string( + use_inbound_webhook_on_number + ), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(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, @@ -762,47 +1489,102 @@ async def create_async( :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/sms/services#sticky-sender) on the Service instance. - :param mms_converter: Whether to enable the [MMS Converter](https://www.twilio.com/docs/sms/services#mms-converter) for messages sent through the Service instance. - :param smart_encoding: Whether to enable [Smart Encoding](https://www.twilio.com/docs/sms/services#smart-encoding) for messages sent through the Service instance. + :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: Whether to enable [Fallback to Long Code](https://www.twilio.com/docs/sms/services#fallback-to-long-code) for messages sent through the Service instance. - :param area_code_geomatch: Whether to enable [Area Code Geomatch](https://www.twilio.com/docs/sms/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`. + :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. Examples: [notification, marketing, verification, poll ..]. + :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": sticky_sender, - "MmsConverter": mms_converter, - "SmartEncoding": smart_encoding, - "ScanMessageContent": scan_message_content, - "FallbackToLongCode": fallback_to_long_code, - "AreaCodeGeomatch": area_code_geomatch, - "ValidityPeriod": validity_period, - "SynchronousValidation": synchronous_validation, - "Usecase": usecase, - "UseInboundWebhookOnNumber": 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, ) + return ServiceInstance(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, + 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 - return ServiceInstance(self._version, payload) + :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._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, + ) + instance = ServiceInstance(self._version, payload) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def stream( self, @@ -854,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, @@ -873,6 +1705,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -899,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( @@ -907,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, @@ -931,7 +1815,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -958,11 +1848,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 92d81e9fc4..2d91b12ebd 100644 --- a/twilio/rest/messaging/v1/service/alpha_sender.py +++ b/twilio/rest/messaging/v1/service/alpha_sender.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class AlphaSenderInstance(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. @@ -62,6 +61,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[AlphaSenderContext] = None @property @@ -98,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 @@ -116,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 @@ -127,6 +163,7 @@ def __repr__(self) -> str: class AlphaSenderContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the AlphaSenderContext @@ -146,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 @@ -153,9 +204,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -165,9 +238,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AlphaSenderInstance 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) -> AlphaSenderInstance: @@ -177,18 +274,45 @@ def fetch(self) -> AlphaSenderInstance: :returns: The fetched AlphaSenderInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return AlphaSenderInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AlphaSenderInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AlphaSenderInstance: """ @@ -197,18 +321,29 @@ async def fetch_async(self) -> AlphaSenderInstance: :returns: The fetched AlphaSenderInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AlphaSenderInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return AlphaSenderInstance( + 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: """ @@ -221,12 +356,14 @@ def __repr__(self) -> str: class AlphaSenderPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AlphaSenderInstance: """ Build an instance of AlphaSenderInstance :param payload: Payload response from the API """ + return AlphaSenderInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -241,6 +378,7 @@ def __repr__(self) -> str: class AlphaSenderList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the AlphaSenderList @@ -257,54 +395,108 @@ 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 - - :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. + Internal helper for create operation - :returns: The created AlphaSenderInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "AlphaSender": alpha_sender, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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) -> 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( { "AlphaSender": alpha_sender, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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) -> 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, @@ -355,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, @@ -374,6 +616,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -400,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( @@ -408,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, @@ -432,8 +726,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AlphaSenderPage(self._version, response, self._solution) + 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 AlphaSenderPage(self._version, response, solution=self._solution) async def page_async( self, @@ -459,10 +759,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return AlphaSenderPage(self._version, response, self._solution) + 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: """ @@ -474,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: """ @@ -486,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 new file mode 100644 index 0000000000..37a8f4d9a5 --- /dev/null +++ b/twilio/rest/messaging/v1/service/channel_sender.py @@ -0,0 +1,907 @@ +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 ChannelSenderInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ChannelSender resource. + :ivar messaging_service_sid: The SID of the [Service](https://www.twilio.com/docs/messaging/services) the resource is associated with. + :ivar sid: The unique string that we created to identify the ChannelSender resource. + :ivar sender: The unique string that identifies the sender e.g whatsapp:+123456XXXX. + :ivar sender_type: A string value that identifies the sender type e.g WhatsApp, Messenger. + :ivar country_code: The 2-character [ISO Country Code](https://www.iso.org/iso-3166-country-codes.html) of the number. + :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 ChannelSender resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + messaging_service_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.messaging_service_sid: Optional[str] = payload.get("messaging_service_sid") + self.sid: Optional[str] = payload.get("sid") + self.sender: Optional[str] = payload.get("sender") + self.sender_type: Optional[str] = payload.get("sender_type") + self.country_code: Optional[str] = payload.get("country_code") + 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 = { + "messaging_service_sid": messaging_service_sid, + "sid": sid or self.sid, + } + + self._context: Optional[ChannelSenderContext] = None + + @property + def _proxy(self) -> "ChannelSenderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ChannelSenderContext for this ChannelSenderInstance + """ + if self._context is None: + self._context = ChannelSenderContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the ChannelSenderInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched ChannelSenderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "ChannelSenderInstance": + """ + Asynchronous coroutine to fetch the ChannelSenderInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelSenderContext(InstanceContext): + + def __init__(self, version: Version, messaging_service_sid: str, sid: str): + """ + Initialize the ChannelSenderContext + + :param version: Version that contains the resource + :param messaging_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 ChannelSender resource to fetch. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + "sid": sid, + } + self._uri = "/Services/{messaging_service_sid}/ChannelSenders/{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 ChannelSenderInstance + + + :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 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 ChannelSenderInstance + + + :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 ChannelSenderInstance 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) -> ChannelSenderInstance: + """ + Fetch the ChannelSenderInstance + + + :returns: The fetched ChannelSenderInstance + """ + payload, _, _ = self._fetch() + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChannelSenderInstance and return response metadata + + + :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" + + 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, + messaging_service_sid=self._solution["messaging_service_sid"], + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ChannelSenderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ChannelSenderInstance: + """ + Build an instance of ChannelSenderInstance + + :param payload: Payload response from the API + """ + + return ChannelSenderInstance( + self._version, + payload, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ChannelSenderList(ListResource): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the ChannelSenderList + + :param version: Version that contains the resource + :param messaging_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 = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/Services/{messaging_service_sid}/ChannelSenders".format( + **self._solution + ) + + def _create(self, sid: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + 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"], + ) + + def create_with_http_info(self, sid: str) -> ApiResponse: + """ + 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 = 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( + { + "Sid": 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, 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, + page_size: Optional[int] = None, + ) -> Iterator[ChannelSenderInstance]: + """ + Streams ChannelSenderInstance 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[ChannelSenderInstance]: + """ + Asynchronously streams ChannelSenderInstance 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 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, + page_size: Optional[int] = None, + ) -> List[ChannelSenderInstance]: + """ + Lists ChannelSenderInstance 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[ChannelSenderInstance]: + """ + Asynchronously lists ChannelSenderInstance 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 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, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> ChannelSenderPage: + """ + Retrieve a single page of ChannelSenderInstance 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 ChannelSenderInstance + """ + data = values.of( + { + "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 ChannelSenderPage(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, + ) -> ChannelSenderPage: + """ + Asynchronously retrieve a single page of ChannelSenderInstance 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 ChannelSenderInstance + """ + data = values.of( + { + "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 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: + """ + Retrieve a specific page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelSenderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return ChannelSenderPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> ChannelSenderPage: + """ + Asynchronously retrieve a specific page of ChannelSenderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of ChannelSenderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return ChannelSenderPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> ChannelSenderContext: + """ + Constructs a ChannelSenderContext + + :param sid: The SID of the ChannelSender resource to fetch. + """ + return ChannelSenderContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __call__(self, sid: str) -> ChannelSenderContext: + """ + Constructs a ChannelSenderContext + + :param sid: The SID of the ChannelSender resource to fetch. + """ + return ChannelSenderContext( + self._version, + messaging_service_sid=self._solution["messaging_service_sid"], + sid=sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/messaging/v1/service/phone_number.py b/twilio/rest/messaging/v1/service/phone_number.py index c01c76a3b7..9992fd0102 100644 --- a/twilio/rest/messaging/v1/service/phone_number.py +++ b/twilio/rest/messaging/v1/service/phone_number.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class PhoneNumberInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the PhoneNumber resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. @@ -64,6 +63,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[PhoneNumberContext] = None @property @@ -100,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 @@ -118,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 @@ -129,6 +165,7 @@ def __repr__(self) -> str: class PhoneNumberContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the PhoneNumberContext @@ -148,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 @@ -155,9 +206,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -167,9 +240,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance 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) -> PhoneNumberInstance: @@ -179,18 +276,45 @@ def fetch(self) -> PhoneNumberInstance: :returns: The fetched PhoneNumberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return PhoneNumberInstance( + 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, 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) -> PhoneNumberInstance: """ @@ -199,18 +323,29 @@ async def fetch_async(self) -> PhoneNumberInstance: :returns: The fetched PhoneNumberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return PhoneNumberInstance( + 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: """ @@ -223,12 +358,14 @@ def __repr__(self) -> str: class PhoneNumberPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: """ Build an instance of PhoneNumberInstance :param payload: Payload response from the API """ + return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -243,6 +380,7 @@ def __repr__(self) -> str: class PhoneNumberList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the PhoneNumberList @@ -259,54 +397,108 @@ 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 - - :param phone_number_sid: The SID of the Phone Number being added to the Service. + Internal helper for create operation - :returns: The created PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "PhoneNumberSid": phone_number_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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_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( { "PhoneNumberSid": phone_number_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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_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, @@ -357,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, @@ -376,6 +618,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -402,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( @@ -410,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, @@ -434,8 +728,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return PhoneNumberPage(self._version, response, self._solution) + 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 PhoneNumberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -461,10 +761,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return PhoneNumberPage(self._version, response, self._solution) + 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: """ @@ -476,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: """ @@ -488,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 104f03f6ec..f1e7039dfc 100644 --- a/twilio/rest/messaging/v1/service/short_code.py +++ b/twilio/rest/messaging/v1/service/short_code.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ 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. @@ -64,6 +63,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[ShortCodeContext] = None @property @@ -100,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 @@ -118,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 @@ -129,6 +165,7 @@ def __repr__(self) -> str: class ShortCodeContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the ShortCodeContext @@ -146,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 @@ -153,9 +204,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -165,9 +238,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ShortCodeInstance 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) -> ShortCodeInstance: @@ -177,18 +274,45 @@ def fetch(self) -> ShortCodeInstance: :returns: The fetched ShortCodeInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ShortCodeInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ShortCodeInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ShortCodeInstance: """ @@ -197,18 +321,29 @@ async def fetch_async(self) -> ShortCodeInstance: :returns: The fetched ShortCodeInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ShortCodeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return ShortCodeInstance( + 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: """ @@ -221,12 +356,14 @@ def __repr__(self) -> str: 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"] ) @@ -241,6 +378,7 @@ def __repr__(self) -> str: class ShortCodeList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the ShortCodeList @@ -257,54 +395,108 @@ 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 - - :param short_code_sid: The SID of the ShortCode resource being added to the Service. + Internal helper for create operation - :returns: The created ShortCodeInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "ShortCodeSid": short_code_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "ShortCodeSid": short_code_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -355,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, @@ -374,6 +616,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -400,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( @@ -408,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, @@ -432,8 +726,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ShortCodePage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -459,10 +759,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ShortCodePage(self._version, response, self._solution) + 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: """ @@ -474,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: """ @@ -486,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 5aa45fc162..ba3bfdc125 100644 --- a/twilio/rest/messaging/v1/service/us_app_to_person.py +++ b/twilio/rest/messaging/v1/service/us_app_to_person.py @@ -12,10 +12,10 @@ 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 @@ -24,17 +24,19 @@ class UsAppToPersonInstance(InstanceResource): - """ :ivar sid: The unique string that identifies a US A2P Compliance resource `QE2c6890da8086d771620e9b13fadeba0b`. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that the Campaign belongs to. :ivar brand_registration_sid: The unique string to identify the A2P brand. - :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services/api) that the resource is associated with. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) that the resource is associated with. :ivar description: A short description of what this SMS campaign does. Min length: 40 characters. Max length: 4096 characters. - :ivar message_samples: Message samples, at least 1 and up to 5 sample messages (at least 2 for starter/sole proprietor), >=20 chars, <=1024 chars each. + :ivar 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. :ivar us_app_to_person_usecase: A2P Campaign Use Case. Examples: [ 2FA, EMERGENCY, MARKETING, SOLE_PROPRIETOR...]. SOLE_PROPRIETOR campaign use cases can only be created by SOLE_PROPRIETOR Brands, and there can only be one SOLE_PROPRIETOR campaign created per SOLE_PROPRIETOR Brand. :ivar has_embedded_links: Indicate that this SMS campaign will send messages that contain links. :ivar has_embedded_phone: Indicates that this SMS campaign will send messages that contain phone numbers. + :ivar subscriber_opt_in: A boolean that specifies whether campaign has Subscriber Optin or not. + :ivar age_gated: A boolean that specifies whether campaign is age gated or not. + :ivar direct_lending: A boolean that specifies whether campaign allows direct lending or not. :ivar campaign_status: Campaign status. Examples: IN_PROGRESS, VERIFIED, FAILED. :ivar campaign_id: The Campaign Registry (TCR) Campaign ID. :ivar is_externally_registered: Indicates whether the campaign was registered externally or not. @@ -50,6 +52,9 @@ class UsAppToPersonInstance(InstanceResource): :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 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__( @@ -74,6 +79,9 @@ def __init__( ) self.has_embedded_links: Optional[bool] = payload.get("has_embedded_links") self.has_embedded_phone: Optional[bool] = payload.get("has_embedded_phone") + self.subscriber_opt_in: Optional[bool] = payload.get("subscriber_opt_in") + self.age_gated: Optional[bool] = payload.get("age_gated") + self.direct_lending: Optional[bool] = payload.get("direct_lending") self.campaign_status: Optional[str] = payload.get("campaign_status") self.campaign_id: Optional[str] = payload.get("campaign_id") self.is_externally_registered: Optional[bool] = payload.get( @@ -95,11 +103,17 @@ 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 @@ -136,23 +150,247 @@ 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, + 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 + """ + return self._proxy.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, + ) + + 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": + """ + Asynchronous coroutine to 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 + """ + return await self._proxy.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, + ) + + 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: """ @@ -165,13 +403,14 @@ def __repr__(self) -> str: class UsAppToPersonContext(InstanceContext): + def __init__(self, version: Version, messaging_service_sid: str, sid: str): """ Initialize the UsAppToPersonContext :param version: Version that contains the resource - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services/api) to fetch the resource from. - :param sid: The SID of the US A2P Compliance resource to fetch `QE2c6890da8086d771620e9b13fadeba0b`. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services/api) to update the resource from. + :param sid: The SID of the US A2P Compliance resource to update `QE2c6890da8086d771620e9b13fadeba0b`. """ super().__init__(version) @@ -184,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 @@ -191,9 +444,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -203,24 +478,52 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) + success, _, _ = await self._delete_async() + return success - def fetch(self) -> UsAppToPersonInstance: + async def delete_with_http_info_async(self) -> ApiResponse: """ - Fetch the UsAppToPersonInstance + Asynchronous coroutine that deletes the UsAppToPersonInstance and return response metadata - :returns: The fetched UsAppToPersonInstance + :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, x_twilio_api_version: Union[str, object] = values.unset) -> tuple: """ + Internal 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 - payload = self._version.fetch( - method="GET", - uri=self._uri, + headers["Accept"] = "application/json" + + 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, @@ -228,177 +531,682 @@ 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 = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, status_code, headers = self._fetch( + x_twilio_api_version=x_twilio_api_version ) - - return UsAppToPersonInstance( + 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: + async def _fetch_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> tuple: """ - Provide a friendly representation + Internal async helper for fetch operation - :returns: Machine friendly representation + Returns: + tuple: (payload, status_code, headers) """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) + headers = values.of({}) -class UsAppToPersonPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> UsAppToPersonInstance: + 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" + + 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: """ - Build an instance of UsAppToPersonInstance + Asynchronous coroutine to fetch the UsAppToPersonInstance - :param payload: Payload response from the API + :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, messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], ) - def __repr__(self) -> str: + async def fetch_with_http_info_async( + self, x_twilio_api_version: Union[str, object] = values.unset + ) -> ApiResponse: """ - Provide a friendly representation + Asynchronous coroutine to fetch the UsAppToPersonInstance and return response metadata - :returns: Machine friendly representation + :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 "" + 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, + 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 helper for update operation -class UsAppToPersonList(ListResource): - def __init__(self, version: Version, messaging_service_sid: str): + Returns: + tuple: (payload, status_code, headers) """ - Initialize the UsAppToPersonList - :param version: Version that contains the resource - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services/api) to fetch the resource from. + data = values.of( + { + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "MessageSamples": serialize.map(message_samples, lambda e: e), + "MessageFlow": message_flow, + "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({}) - """ - super().__init__(version) + 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 - # Path Solution - self._solution = { - "messaging_service_sid": messaging_service_sid, - } - self._uri = "/Services/{messaging_service_sid}/Compliance/Usa2p".format( - **self._solution + 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 create( + def update( 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, - 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, + 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: """ - Create the UsAppToPersonInstance + Update 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: Message samples, at least 1 and up to 5 sample messages (at least 2 for sole proprietor), >=20 chars, <=1024 chars each. - :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 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 created UsAppToPersonInstance + :returns: The updated UsAppToPersonInstance """ - data = values.of( - { - "BrandRegistrationSid": brand_registration_sid, - "Description": description, - "MessageFlow": message_flow, - "MessageSamples": serialize.map(message_samples, lambda e: e), - "UsAppToPersonUsecase": us_app_to_person_usecase, - "HasEmbeddedLinks": has_embedded_links, - "HasEmbeddedPhone": has_embedded_phone, - "OptInMessage": opt_in_message, - "OptOutMessage": opt_out_message, - "HelpMessage": help_message, - "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), - "OptOutKeywords": serialize.map(opt_out_keywords, lambda e: e), - "HelpKeywords": serialize.map(help_keywords, lambda e: e), - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, messaging_service_sid=self._solution["messaging_service_sid"], + sid=self._solution["sid"], ) - async def create_async( + def update_with_http_info( 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, - 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, - ) -> UsAppToPersonInstance: + 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: """ - Asynchronously create the UsAppToPersonInstance + Update the UsAppToPersonInstance and return response metadata - :param brand_registration_sid: A2P Brand Registration SID + :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 = 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( + { + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "MessageSamples": serialize.map(message_samples, lambda e: e), + "MessageFlow": message_flow, + "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" + + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, 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, + ) -> UsAppToPersonInstance: + """ + Asynchronous coroutine to 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, _, _ = 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 message_samples: Message samples, at least 1 and up to 5 sample messages (at least 2 for sole proprietor), >=20 chars, <=1024 chars each. + :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 "".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, + messaging_service_sid=self._solution["messaging_service_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class UsAppToPersonList(ListResource): + + def __init__(self, version: Version, messaging_service_sid: str): + """ + Initialize the UsAppToPersonList + + :param version: Version that contains the resource + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to fetch the resource from. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "messaging_service_sid": messaging_service_sid, + } + self._uri = "/Services/{messaging_service_sid}/Compliance/Usa2p".format( + **self._solution + ) + + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + "Description": description, + "MessageFlow": message_flow, + "MessageSamples": serialize.map(message_samples, lambda e: e), + "UsAppToPersonUsecase": us_app_to_person_usecase, + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), + "OptInMessage": opt_in_message, + "OptOutMessage": opt_out_message, + "HelpMessage": help_message, + "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), + "OptOutKeywords": serialize.map(opt_out_keywords, lambda e: e), + "HelpKeywords": serialize.map(help_keywords, lambda e: e), + "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["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, + 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"], + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "BrandRegistrationSid": brand_registration_sid, @@ -406,31 +1214,188 @@ async def create_async( "MessageFlow": message_flow, "MessageSamples": serialize.map(message_samples, lambda e: e), "UsAppToPersonUsecase": us_app_to_person_usecase, - "HasEmbeddedLinks": has_embedded_links, - "HasEmbeddedPhone": has_embedded_phone, + "HasEmbeddedLinks": serialize.boolean_to_string(has_embedded_links), + "HasEmbeddedPhone": serialize.boolean_to_string(has_embedded_phone), "OptInMessage": opt_in_message, "OptOutMessage": opt_out_message, "HelpMessage": help_message, "OptInKeywords": serialize.map(opt_in_keywords, lambda e: e), "OptOutKeywords": serialize.map(opt_out_keywords, lambda e: e), "HelpKeywords": serialize.map(help_keywords, lambda e: e), + "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", } ) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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]: @@ -440,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 @@ -450,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]: @@ -465,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 @@ -475,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]: @@ -489,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 @@ -498,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, ) @@ -507,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]: @@ -515,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 @@ -524,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, @@ -542,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 @@ -550,17 +1644,30 @@ def page( """ data = values.of( { + "X-Twilio-Api-Version": x_twilio_api_version, "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UsAppToPersonPage(self._version, response, self._solution) + 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, 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, @@ -569,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 @@ -577,16 +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( + { + "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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UsAppToPersonPage(self._version, response, self._solution) + 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: """ @@ -598,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: """ @@ -610,13 +1814,13 @@ 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: """ Constructs a UsAppToPersonContext - :param sid: The SID of the US A2P Compliance resource to fetch `QE2c6890da8086d771620e9b13fadeba0b`. + :param sid: The SID of the US A2P Compliance resource to update `QE2c6890da8086d771620e9b13fadeba0b`. """ return UsAppToPersonContext( self._version, @@ -628,7 +1832,7 @@ def __call__(self, sid: str) -> UsAppToPersonContext: """ Constructs a UsAppToPersonContext - :param sid: The SID of the US A2P Compliance resource to fetch `QE2c6890da8086d771620e9b13fadeba0b`. + :param sid: The SID of the US A2P Compliance resource to update `QE2c6890da8086d771620e9b13fadeba0b`. """ return UsAppToPersonContext( self._version, 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 572434a3d9..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 @@ -12,8 +12,9 @@ Do not edit the class manually. """ - -from typing import Any, Dict, List, Optional +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 @@ -21,7 +22,6 @@ class UsAppToPersonUsecaseInstance(InstanceResource): - """ :ivar us_app_to_person_usecases: Human readable name, code, description and post_approval_required (indicates whether or not post approval is required for this Use Case) of A2P Campaign Use Cases. """ @@ -31,7 +31,7 @@ def __init__( ): super().__init__(version) - self.us_app_to_person_usecases: Optional[List[object]] = payload.get( + self.us_app_to_person_usecases: Optional[List[Dict[str, object]]] = payload.get( "us_app_to_person_usecases" ) @@ -50,12 +50,13 @@ def __repr__(self) -> str: class UsAppToPersonUsecaseList(ListResource): + def __init__(self, version: Version, messaging_service_sid: str): """ Initialize the UsAppToPersonUsecaseList :param version: Version that contains the resource - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/services/api) to fetch the resource from. + :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/messaging/api/service-resource) to fetch the resource from. """ super().__init__(version) @@ -70,34 +71,124 @@ def __init__(self, version: Version, messaging_service_sid: str): ) ) - def fetch(self) -> UsAppToPersonUsecaseInstance: + def _fetch( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> tuple: """ - Asynchronously fetch the UsAppToPersonUsecaseInstance + Internal helper for fetch operation - :returns: The fetched UsAppToPersonUsecaseInstance + Returns: + tuple: (payload, status_code, headers) + """ + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + } + ) + + 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: """ - payload = self._version.fetch(method="GET", uri=self._uri) + 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(self) -> UsAppToPersonUsecaseInstance: + def fetch_with_http_info( + self, brand_registration_sid: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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"}) + + headers["Accept"] = "application/json" + + params = values.of( + { + "BrandRegistrationSid": brand_registration_sid, + } + ) + + 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._version.fetch_async(method="GET", uri=self._uri) - + 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 249aa6874e..844e16054e 100644 --- a/twilio/rest/messaging/v1/tollfree_verification.py +++ b/twilio/rest/messaging/v1/tollfree_verification.py @@ -12,10 +12,10 @@ 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 @@ -24,12 +24,42 @@ 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" PAPER_FORM = "PAPER_FORM" 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" @@ -37,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. @@ -56,9 +89,9 @@ class Status(object): :ivar business_contact_first_name: The first name of the contact for the business or organization using the Tollfree number. :ivar business_contact_last_name: The last name of the contact for the business or organization using the Tollfree number. :ivar business_contact_email: The email address of the contact for the business or organization using the Tollfree number. - :ivar business_contact_phone: The phone number 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. @@ -66,10 +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__( @@ -115,17 +169,17 @@ 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( "production_message_sample" ) self.opt_in_image_urls: Optional[List[str]] = payload.get("opt_in_image_urls") - self.opt_in_type: Optional[ - "TollfreeVerificationInstance.OptInType" - ] = payload.get("opt_in_type") + self.opt_in_type: Optional["TollfreeVerificationInstance.OptInType"] = ( + payload.get("opt_in_type") + ) self.message_volume: Optional[str] = payload.get("message_volume") self.additional_information: Optional[str] = payload.get( "additional_information" @@ -133,16 +187,60 @@ 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" ) self.url: Optional[str] = payload.get("url") + self.rejection_reason: Optional[str] = payload.get("rejection_reason") + self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) + self.edit_expiration: Optional[datetime] = deserialize.iso8601_datetime( + 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 @@ -160,6 +258,42 @@ def _proxy(self) -> "TollfreeVerificationContext": ) return self._context + def delete(self) -> bool: + """ + Deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the TollfreeVerificationInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 @@ -178,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, @@ -202,6 +354,27 @@ def update( 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, ) -> "TollfreeVerificationInstance": """ Update the TollfreeVerificationInstance @@ -209,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. @@ -225,7 +398,22 @@ def update( :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 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 """ @@ -250,6 +438,21 @@ def update( 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_async( @@ -276,6 +479,27 @@ async def update_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, + 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 @@ -283,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. @@ -299,7 +523,22 @@ async def update_async( :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 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 """ @@ -324,73 +563,24 @@ async def update_async( 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: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) - return "".format(context) - - -class TollfreeVerificationContext(InstanceContext): - def __init__(self, version: Version, sid: str): - """ - Initialize the TollfreeVerificationContext - - :param version: Version that contains the resource - :param sid: The unique string to identify Tollfree Verification. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Tollfree/Verifications/{sid}".format(**self._solution) - - def fetch(self) -> TollfreeVerificationInstance: - """ - Fetch the TollfreeVerificationInstance - - - :returns: The fetched TollfreeVerificationInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return TollfreeVerificationInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> TollfreeVerificationInstance: - """ - Asynchronous coroutine to fetch the TollfreeVerificationInstance - - - :returns: The fetched TollfreeVerificationInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return TollfreeVerificationInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( + def update_with_http_info( self, business_name: Union[str, object] = values.unset, business_website: Union[str, object] = values.unset, @@ -414,14 +604,35 @@ def update( 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, - ) -> 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: """ - Update the TollfreeVerificationInstance + 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 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. @@ -437,46 +648,64 @@ def update( :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. - - :returns: The updated TollfreeVerificationInstance + :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 """ - 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, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return TollfreeVerificationInstance( - self._version, payload, sid=self._solution["sid"] + 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_async( + async def update_with_http_info_async( self, business_name: Union[str, object] = values.unset, business_website: Union[str, object] = values.unset, @@ -500,14 +729,35 @@ async def update_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, - ) -> 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: """ - Asynchronous coroutine to update the TollfreeVerificationInstance + 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 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. @@ -523,43 +773,61 @@ async def update_async( :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. - - :returns: The updated TollfreeVerificationInstance + :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 """ - 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, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return TollfreeVerificationInstance( - self._version, payload, sid=self._solution["sid"] + 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: @@ -569,38 +837,1048 @@ 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 TollfreeVerificationPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> TollfreeVerificationInstance: +class TollfreeVerificationContext(InstanceContext): + + def __init__(self, version: Version, sid: str): """ - Build an instance of TollfreeVerificationInstance + Initialize the TollfreeVerificationContext - :param payload: Payload response from the API + :param version: Version that contains the resource + :param sid: The unique string to identify Tollfree Verification. """ - return TollfreeVerificationInstance(self._version, payload) + super().__init__(version) - def __repr__(self) -> str: + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/Tollfree/Verifications/{sid}".format(**self._solution) + + def _delete(self) -> tuple: """ - Provide a friendly representation + Internal helper for delete operation - :returns: Machine friendly representation + Returns: + tuple: (success_boolean, status_code, headers) """ - return "" + headers = values.of({}) -class TollfreeVerificationList(ListResource): - def __init__(self, version: Version): + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + + def delete(self) -> bool: """ - Initialize the TollfreeVerificationList + Deletes the TollfreeVerificationInstance - :param version: Version that contains the resource + :returns: True if delete succeeds, False otherwise """ - super().__init__(version) + success, _, _ = self._delete() + return success - self._uri = "/Tollfree/Verifications" + 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 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 TollfreeVerificationInstance + + + :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 TollfreeVerificationInstance 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) -> TollfreeVerificationInstance: + """ + Fetch the TollfreeVerificationInstance + + + :returns: The fetched TollfreeVerificationInstance + """ + payload, _, _ = self._fetch() + return TollfreeVerificationInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TollfreeVerificationInstance and return response metadata + + + :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" + + 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"], + ) + + 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, + 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 helper for update 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, + "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, + "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({}) + + 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, + 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, + ) -> 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 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: The updated TollfreeVerificationInstance + """ + 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 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 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 = 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) + + 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( + { + "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, + "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({}) + + 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, + 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, + ) -> 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 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: 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 "".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 "" + + +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( + { + "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 self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def create( self, @@ -627,6 +1905,26 @@ def create( 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 @@ -634,7 +1932,7 @@ def create( :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. @@ -652,11 +1950,250 @@ def create( :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 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, @@ -682,18 +2219,163 @@ def create( "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 - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + :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_async( + async def create_with_http_info_async( self, business_name: str, business_website: str, @@ -718,14 +2400,34 @@ async def create_async( 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: + 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 + 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 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. @@ -743,51 +2445,74 @@ async def create_async( :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 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. - - :returns: The created TollfreeVerificationInstance + :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 """ - 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, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, ) -> Iterator[TollfreeVerificationInstance]: @@ -799,6 +2524,9 @@ def stream( :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 @@ -812,6 +2540,9 @@ def stream( page = self.page( 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"], ) @@ -821,6 +2552,9 @@ async def stream_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, ) -> AsyncIterator[TollfreeVerificationInstance]: @@ -832,6 +2566,9 @@ async def stream_async( :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 @@ -845,15 +2582,103 @@ async def stream_async( page = await self.page_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"], ) 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]: @@ -864,6 +2689,9 @@ def list( :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 @@ -873,10 +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, ) @@ -886,6 +2718,9 @@ async def list_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, ) -> List[TollfreeVerificationInstance]: @@ -896,6 +2731,9 @@ async def list_async( :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 @@ -905,20 +2743,107 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_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, ) ] + 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, @@ -929,6 +2854,9 @@ def page( :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 @@ -939,19 +2867,31 @@ def page( { "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, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 TollfreeVerificationPage(self._version, response) async def page_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, @@ -962,6 +2902,9 @@ async def page_async( :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 @@ -972,17 +2915,124 @@ async def page_async( { "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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 ba65e8b106..46e9bf390f 100644 --- a/twilio/rest/messaging/v1/usecase.py +++ b/twilio/rest/messaging/v1/usecase.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class UsecaseInstance(InstanceResource): - """ :ivar usecases: Human readable use case details (usecase, description and purpose) of Messaging Service Use Cases. """ @@ -29,7 +29,7 @@ class UsecaseInstance(InstanceResource): def __init__(self, version: Version, payload: Dict[str, Any]): super().__init__(version) - self.usecases: Optional[List[object]] = payload.get("usecases") + self.usecases: Optional[List[Dict[str, object]]] = payload.get("usecases") def __repr__(self) -> str: """ @@ -42,6 +42,7 @@ def __repr__(self) -> str: class UsecaseList(ListResource): + def __init__(self, version: Version): """ Initialize the UsecaseList @@ -53,26 +54,78 @@ def __init__(self, version: Version): self._uri = "/Services/Usecases" + 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) -> UsecaseInstance: """ - Asynchronously fetch the UsecaseInstance + Fetch the UsecaseInstance + :returns: The fetched UsecaseInstance """ - payload = self._version.fetch(method="GET", uri=self._uri) - + payload, _, _ = self._fetch() return UsecaseInstance(self._version, payload) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UsecaseInstance and return response metadata + + + :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" + + 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._version.fetch_async(method="GET", uri=self._uri) - + 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 "" diff --git a/twilio/rest/messaging/v2/channels_sender.py b/twilio/rest/messaging/v2/channels_sender.py new file mode 100644 index 0000000000..46d944f1ff --- /dev/null +++ b/twilio/rest/messaging/v2/channels_sender.py @@ -0,0 +1,1985 @@ +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:` format. + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + 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, + "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 configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + 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 { + "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:` format. + :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.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 "".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:` format. + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + 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, + "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 configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + 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 { + "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 "".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 "" + + +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:` format. + :ivar configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + self.sender_id: Optional[str] = payload.get("sender_id") + 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, + "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 configuration: + :ivar webhook: + :ivar profile: + """ + + def __init__(self, payload: Dict[str, Any]): + + 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 { + "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 "" 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 "".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 "".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 "" 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 "" + + +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 "" diff --git a/twilio/rest/preview/deployed_devices/__init__.py b/twilio/rest/messaging/v3/__init__.py similarity index 59% rename from twilio/rest/preview/deployed_devices/__init__.py rename to twilio/rest/messaging/v3/__init__.py index 30d6288565..20229f1936 100644 --- a/twilio/rest/preview/deployed_devices/__init__.py +++ b/twilio/rest/messaging/v3/__init__.py @@ -4,7 +4,7 @@ | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - Twilio - Preview + Twilio - Messaging This is the public Twilio REST API. NOTE: This class is auto generated by OpenAPI Generator. @@ -15,28 +15,29 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain -from twilio.rest.preview.deployed_devices.fleet import FleetList +from twilio.rest.messaging.v3.typing_indicator import TypingIndicatorList -class DeployedDevices(Version): +class V3(Version): + def __init__(self, domain: Domain): """ - Initialize the DeployedDevices version of Preview + Initialize the V3 version of Messaging - :param domain: The Twilio.preview domain + :param domain: The Twilio.messaging domain """ - super().__init__(domain, "DeployedDevices") - self._fleets: Optional[FleetList] = None + super().__init__(domain, "v3") + self._typing_indicator: Optional[TypingIndicatorList] = None @property - def fleets(self) -> FleetList: - if self._fleets is None: - self._fleets = FleetList(self) - return self._fleets + 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 "" + return "" diff --git a/twilio/rest/messaging/v3/typing_indicator.py b/twilio/rest/messaging/v3/typing_indicator.py new file mode 100644 index 0000000000..2fc385b528 --- /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 \"APPLE\". + :ivar message_id: The SID of a recent inbound message from the recipient. Must be an SM or MM SID format. + :ivar _from: The Apple Messages for Business identifier of the sender (business). + :ivar to: The Apple Messages for Business identifier of the recipient (customer). + :ivar event: The type of typing event. \"START\" indicates the agent began typing, \"END\" indicates the agent stopped 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 "" + + +class TypingIndicatorList(ListResource): + + class TypingIndicatorRequest(object): + """ + :ivar channel: The messaging channel. Must be \"APPLE\". + :ivar message_id: The SID of a recent inbound message from the recipient. Must be an SM or MM SID format. + :ivar _from: The Apple Messages for Business identifier of the sender (business). + :ivar to: The Apple Messages for Business identifier of the recipient (customer). + :ivar event: The type of typing event. \"START\" indicates the agent began typing, \"END\" indicates the agent stopped 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 "" 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 d47ed845bd..0000000000 --- a/twilio/rest/microvisor/v1/__init__.py +++ /dev/null @@ -1,66 +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 "" diff --git a/twilio/rest/microvisor/v1/account_config.py b/twilio/rest/microvisor/v1/account_config.py deleted file mode 100644 index 7d8119a3de..0000000000 --- a/twilio/rest/microvisor/v1/account_config.py +++ /dev/null @@ -1,552 +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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AccountConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> AccountConfigInstance: - """ - Fetch the AccountConfigInstance - - - :returns: The fetched AccountConfigInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" diff --git a/twilio/rest/microvisor/v1/account_secret.py b/twilio/rest/microvisor/v1/account_secret.py deleted file mode 100644 index a7fc4f8969..0000000000 --- a/twilio/rest/microvisor/v1/account_secret.py +++ /dev/null @@ -1,550 +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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AccountSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> AccountSecretInstance: - """ - Fetch the AccountSecretInstance - - - :returns: The fetched AccountSecretInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" diff --git a/twilio/rest/microvisor/v1/app/__init__.py b/twilio/rest/microvisor/v1/app/__init__.py deleted file mode 100644 index e9f547af76..0000000000 --- a/twilio/rest/microvisor/v1/app/__init__.py +++ /dev/null @@ -1,468 +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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AppInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> AppInstance: - """ - Fetch the AppInstance - - - :returns: The fetched AppInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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 "".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 "" - - -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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 dba0240e91..0000000000 --- a/twilio/rest/microvisor/v1/app/app_manifest.py +++ /dev/null @@ -1,188 +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.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 "".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 - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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 "".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 "" diff --git a/twilio/rest/microvisor/v1/device/__init__.py b/twilio/rest/microvisor/v1/device/__init__.py deleted file mode 100644 index 89e4e9f4c2..0000000000 --- a/twilio/rest/microvisor/v1/device/__init__.py +++ /dev/null @@ -1,553 +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.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, - ) -> "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. - - :returns: The updated DeviceInstance - """ - return self._proxy.update( - unique_name=unique_name, - target_app=target_app, - logging_enabled=logging_enabled, - ) - - 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, - ) -> "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. - - :returns: The updated DeviceInstance - """ - return await self._proxy.update_async( - unique_name=unique_name, - target_app=target_app, - logging_enabled=logging_enabled, - ) - - @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 "".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 - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, - ) -> 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. - - :returns: The updated DeviceInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "TargetApp": target_app, - "LoggingEnabled": logging_enabled, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - ) -> 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. - - :returns: The updated DeviceInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "TargetApp": target_app, - "LoggingEnabled": logging_enabled, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 a954727bf0..0000000000 --- a/twilio/rest/microvisor/v1/device/device_config.py +++ /dev/null @@ -1,589 +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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeviceConfigInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> DeviceConfigInstance: - """ - Fetch the DeviceConfigInstance - - - :returns: The fetched DeviceConfigInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 7f2ee0eeb0..0000000000 --- a/twilio/rest/microvisor/v1/device/device_secret.py +++ /dev/null @@ -1,587 +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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeviceSecretInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> DeviceSecretInstance: - """ - Fetch the DeviceSecretInstance - - - :returns: The fetched DeviceSecretInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" diff --git a/twilio/rest/monitor/MonitorBase.py b/twilio/rest/monitor/MonitorBase.py index d63580761f..4c5c6ebcd6 100644 --- a/twilio/rest/monitor/MonitorBase.py +++ b/twilio/rest/monitor/MonitorBase.py @@ -17,6 +17,7 @@ class MonitorBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Monitor Domain diff --git a/twilio/rest/monitor/v1/__init__.py b/twilio/rest/monitor/v1/__init__.py index fcf06738fa..e892612b3b 100644 --- a/twilio/rest/monitor/v1/__init__.py +++ b/twilio/rest/monitor/v1/__init__.py @@ -20,6 +20,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Monitor diff --git a/twilio/rest/monitor/v1/alert.py b/twilio/rest/monitor/v1/alert.py index b3c44374e5..f7666a0e3b 100644 --- a/twilio/rest/monitor/v1/alert.py +++ b/twilio/rest/monitor/v1/alert.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class AlertInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Alert resource. :ivar alert_text: The text of the alert. @@ -81,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AlertContext] = None @property @@ -116,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 @@ -127,6 +145,7 @@ def __repr__(self) -> str: class AlertContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the AlertContext @@ -142,6 +161,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Alerts/{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) -> AlertInstance: """ Fetch the AlertInstance @@ -149,17 +184,43 @@ def fetch(self) -> AlertInstance: :returns: The fetched AlertInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AlertInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AlertInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AlertInstance: """ @@ -168,17 +229,27 @@ async def fetch_async(self) -> AlertInstance: :returns: The fetched AlertInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AlertInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AlertInstance( + 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: """ @@ -191,12 +262,14 @@ def __repr__(self) -> str: class AlertPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AlertInstance: """ Build an instance of AlertInstance :param payload: Payload response from the API """ + return AlertInstance(self._version, payload) def __repr__(self) -> str: @@ -209,6 +282,7 @@ def __repr__(self) -> str: class AlertList(ListResource): + def __init__(self, version: Version): """ Initialize the AlertList @@ -292,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, @@ -317,6 +461,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( log_level=log_level, @@ -352,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( @@ -363,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, @@ -396,7 +610,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 AlertPage(self._version, response) async def page_async( @@ -432,11 +652,103 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 63829c43e0..e568c814e1 100644 --- a/twilio/rest/monitor/v1/event.py +++ b/twilio/rest/monitor/v1/event.py @@ -12,10 +12,10 @@ 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 @@ -24,10 +24,9 @@ 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. @@ -67,6 +66,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EventContext] = None @property @@ -102,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 @@ -113,6 +131,7 @@ def __repr__(self) -> str: class EventContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the EventContext @@ -128,6 +147,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Events/{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) -> EventInstance: """ Fetch the EventInstance @@ -135,17 +170,43 @@ def fetch(self) -> EventInstance: :returns: The fetched EventInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EventInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EventInstance: """ @@ -154,17 +215,27 @@ async def fetch_async(self) -> EventInstance: :returns: The fetched EventInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EventInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EventInstance( + 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: """ @@ -177,12 +248,14 @@ def __repr__(self) -> str: class EventPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: """ Build an instance of EventInstance :param payload: Payload response from the API """ + return EventInstance(self._version, payload) def __repr__(self) -> str: @@ -195,6 +268,7 @@ def __repr__(self) -> str: class EventList(ListResource): + def __init__(self, version: Version): """ Initialize the EventList @@ -296,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, @@ -327,6 +489,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( actor_sid=actor_sid, @@ -371,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( @@ -385,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, @@ -427,7 +677,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 EventPage(self._version, response) async def page_async( @@ -472,11 +728,121 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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/NotifyBase.py b/twilio/rest/notify/NotifyBase.py index d8a79bed63..2772ed0959 100644 --- a/twilio/rest/notify/NotifyBase.py +++ b/twilio/rest/notify/NotifyBase.py @@ -17,6 +17,7 @@ class NotifyBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Notify Domain diff --git a/twilio/rest/notify/v1/__init__.py b/twilio/rest/notify/v1/__init__.py index 91942a4f73..90cab95028 100644 --- a/twilio/rest/notify/v1/__init__.py +++ b/twilio/rest/notify/v1/__init__.py @@ -20,6 +20,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Notify diff --git a/twilio/rest/notify/v1/credential.py b/twilio/rest/notify/v1/credential.py index 2b1efcf82a..9bbd8bd0fc 100644 --- a/twilio/rest/notify/v1/credential.py +++ b/twilio/rest/notify/v1/credential.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class CredentialInstance(InstanceResource): + class PushService(object): GCM = "gcm" APN = "apn" @@ -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 @@ -185,6 +283,7 @@ def __repr__(self) -> str: class CredentialContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CredentialContext @@ -200,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 @@ -207,9 +320,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -219,9 +354,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialInstance 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) -> CredentialInstance: @@ -231,17 +390,43 @@ def fetch(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialInstance: """ @@ -250,17 +435,63 @@ async def fetch_async(self) -> CredentialInstance: :returns: The fetched CredentialInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CredentialInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CredentialInstance( + 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, + 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 update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "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" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) def update( self, @@ -283,24 +514,83 @@ def update( :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( { "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -323,24 +613,47 @@ async def update_async( :returns: The updated CredentialInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -353,12 +666,14 @@ def __repr__(self) -> str: 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: @@ -371,6 +686,7 @@ def __repr__(self) -> str: class CredentialList(ListResource): + def __init__(self, version: Version): """ Initialize the CredentialList @@ -382,6 +698,44 @@ def __init__(self, version: Version): self._uri = "/Credentials" + def _create( + 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 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.PushService", @@ -405,25 +759,89 @@ def create( :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( { "Type": type, "FriendlyName": friendly_name, "Certificate": certificate, "PrivateKey": private_key, - "Sandbox": sandbox, + "Sandbox": serialize.boolean_to_string(sandbox), "ApiKey": api_key, "Secret": secret, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CredentialInstance(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, @@ -448,25 +866,51 @@ async def create_async( :returns: The created CredentialInstance """ - data = values.of( - { - "Type": type, - "FriendlyName": friendly_name, - "Certificate": certificate, - "PrivateKey": private_key, - "Sandbox": sandbox, - "ApiKey": api_key, - "Secret": secret, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CredentialInstance(self._version, payload) + :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, @@ -518,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, @@ -537,6 +1031,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -563,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( @@ -571,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, @@ -595,7 +1141,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CredentialPage(self._version, response) async def page_async( @@ -622,11 +1174,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 fa07045470..629a7f2ae2 100644 --- a/twilio/rest/notify/v1/service/__init__.py +++ b/twilio/rest/notify/v1/service/__init__.py @@ -12,10 +12,10 @@ 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 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 @@ -26,7 +26,6 @@ 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. @@ -36,7 +35,7 @@ class ServiceInstance(InstanceResource): :ivar apn_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for APN Bindings. :ivar gcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for GCM Bindings. :ivar fcm_credential_sid: The SID of the [Credential](https://www.twilio.com/docs/notify/api/credential-resource) to use for FCM Bindings. - :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/send-messages#messaging-services) to use for SMS Bindings. In order to send SMS notifications this parameter has to be set. + :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/quickstart#messaging-services) to use for SMS Bindings. In order to send SMS notifications this parameter has to be set. :ivar facebook_messenger_page_id: Deprecated. :ivar 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. :ivar 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. @@ -95,6 +94,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -130,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 @@ -148,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, @@ -171,7 +207,7 @@ def update( :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/send-messages#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :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. @@ -225,7 +261,7 @@ 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 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/send-messages#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :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. @@ -256,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: """ @@ -281,6 +425,7 @@ def __repr__(self) -> str: class ServiceContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ServiceContext @@ -299,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 @@ -306,9 +465,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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: @@ -318,9 +499,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -330,17 +535,43 @@ def fetch(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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: """ @@ -349,19 +580,29 @@ async def fetch_async(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, apn_credential_sid: Union[str, object] = values.unset, @@ -377,27 +618,14 @@ 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/send-messages#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( { "FriendlyName": friendly_name, @@ -409,23 +637,26 @@ def update( "DefaultGcmNotificationProtocolVersion": default_gcm_notification_protocol_version, "FcmCredentialSid": fcm_credential_sid, "DefaultFcmNotificationProtocolVersion": default_fcm_notification_protocol_version, - "LogEnabled": log_enabled, + "LogEnabled": serialize.boolean_to_string(log_enabled), "AlexaSkillId": alexa_skill_id, "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, "DeliveryCallbackUrl": delivery_callback_url, - "DeliveryCallbackEnabled": delivery_callback_enabled, + "DeliveryCallbackEnabled": serialize.boolean_to_string( + delivery_callback_enabled + ), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - async def update_async( + 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, apn_credential_sid: Union[str, object] = values.unset, @@ -443,12 +674,12 @@ 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. :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/send-messages#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :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. @@ -462,37 +693,249 @@ 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": log_enabled, - "AlexaSkillId": alexa_skill_id, - "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, - "DeliveryCallbackUrl": delivery_callback_url, - "DeliveryCallbackEnabled": delivery_callback_enabled, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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( @@ -524,36 +967,258 @@ def __repr__(self) -> str: 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 + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +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, + 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, + 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 create operation - :returns: Machine friendly representation + Returns: + tuple: (payload, status_code, headers) """ - return "" - -class ServiceList(ListResource): - def __init__(self, version: Version): - """ - Initialize the ServiceList + 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"}) - :param version: Version that contains the resource + headers["Content-Type"] = "application/x-www-form-urlencoded" - """ - super().__init__(version) + 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: Union[str, object] = values.unset, apn_credential_sid: Union[str, object] = values.unset, @@ -571,12 +1236,12 @@ def create( delivery_callback_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 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/send-messages#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :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. @@ -590,34 +1255,25 @@ def create( :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": log_enabled, - "AlexaSkillId": alexa_skill_id, - "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, - "DeliveryCallbackUrl": delivery_callback_url, - "DeliveryCallbackEnabled": delivery_callback_enabled, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, ) - return ServiceInstance(self._version, payload) - async def create_async( + async def create_with_http_info_async( self, friendly_name: Union[str, object] = values.unset, apn_credential_sid: Union[str, object] = values.unset, @@ -633,14 +1289,14 @@ async def create_async( 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: + ) -> 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 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/send-messages#messaging-services) to use for SMS Bindings. This parameter must be set in order to send SMS notifications. + :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. @@ -652,34 +1308,26 @@ async def create_async( :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 + :returns: ApiResponse with instance, status code, and 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": log_enabled, - "AlexaSkillId": alexa_skill_id, - "DefaultAlexaNotificationProtocolVersion": default_alexa_notification_protocol_version, - "DeliveryCallbackUrl": delivery_callback_url, - "DeliveryCallbackEnabled": delivery_callback_enabled, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, @@ -737,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, @@ -758,6 +1462,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -787,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( @@ -796,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, @@ -823,7 +1585,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -853,11 +1621,91 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 dba36be720..e380730645 100644 --- a/twilio/rest/notify/v1/service/binding.py +++ b/twilio/rest/notify/v1/service/binding.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,6 +24,7 @@ class BindingInstance(InstanceResource): + class BindingType(object): APN = "apn" GCM = "gcm" @@ -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 @@ -148,6 +186,7 @@ def __repr__(self) -> str: class BindingContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the BindingContext @@ -165,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 @@ -172,9 +225,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -184,9 +259,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BindingInstance 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) -> BindingInstance: @@ -196,18 +295,45 @@ def fetch(self) -> BindingInstance: :returns: The fetched BindingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return BindingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BindingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> BindingInstance: """ @@ -216,18 +342,29 @@ async def fetch_async(self) -> BindingInstance: :returns: The fetched BindingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return BindingInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return BindingInstance( + 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: """ @@ -240,12 +377,14 @@ def __repr__(self) -> str: class BindingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BindingInstance: """ Build an instance of BindingInstance :param payload: Payload response from the API """ + return BindingInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -260,6 +399,7 @@ def __repr__(self) -> str: class BindingList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the BindingList @@ -276,6 +416,44 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Bindings".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Identity": identity, + "BindingType": binding_type, + "Address": address, + "Tag": serialize.map(tag, lambda e: e), + "NotificationProtocolVersion": notification_protocol_version, + "CredentialSid": credential_sid, + "Endpoint": endpoint, + } + ) + 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, identity: str, @@ -299,6 +477,73 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "Identity": identity, @@ -310,15 +555,14 @@ def create( "Endpoint": endpoint, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return BindingInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -344,27 +588,55 @@ async def create_async( :returns: The created BindingInstance """ - data = values.of( - { - "Identity": identity, - "BindingType": binding_type, - "Address": address, - "Tag": serialize.map(tag, lambda e: e), - "NotificationProtocolVersion": notification_protocol_version, - "CredentialSid": credential_sid, - "Endpoint": endpoint, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return BindingInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return BindingInstance( + 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, @@ -444,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, @@ -471,6 +819,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( start_date=start_date, @@ -509,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( @@ -521,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, @@ -557,8 +981,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return BindingPage(self._version, response, self._solution) + 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 BindingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -596,10 +1026,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return BindingPage(self._version, response, self._solution) + 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: """ @@ -611,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: """ @@ -623,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 980dbe633c..a16ef7acf1 100644 --- a/twilio/rest/notify/v1/service/notification.py +++ b/twilio/rest/notify/v1/service/notification.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,6 +23,7 @@ class NotificationInstance(InstanceResource): + class Priority(object): HIGH = "high" LOW = "low" @@ -95,6 +96,7 @@ def __repr__(self) -> str: class NotificationList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the NotificationList @@ -111,6 +113,66 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Notifications".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Body": body, + "Priority": priority, + "Ttl": ttl, + "Title": title, + "Sound": sound, + "Action": action, + "Data": serialize.object(data), + "Apn": serialize.object(apn), + "Gcm": serialize.object(gcm), + "Sms": serialize.object(sms), + "FacebookMessenger": serialize.object(facebook_messenger), + "Fcm": serialize.object(fcm), + "Segment": serialize.map(segment, lambda e: e), + "Alexa": serialize.object(alexa), + "ToBinding": serialize.map(to_binding, lambda e: e), + "DeliveryCallbackUrl": delivery_callback_url, + "Identity": serialize.map(identity, lambda e: e), + "Tag": serialize.map(tag, lambda e: 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.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, body: Union[str, object] = values.unset, @@ -144,7 +206,7 @@ def create( :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/send-messages) 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 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. @@ -156,6 +218,128 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "Body": body, @@ -178,15 +362,14 @@ def create( "Tag": serialize.map(tag, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return NotificationInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -222,7 +405,7 @@ async def create_async( :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/send-messages) 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 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. @@ -234,38 +417,99 @@ async def create_async( :returns: The created NotificationInstance """ - data = values.of( - { - "Body": body, - "Priority": priority, - "Ttl": ttl, - "Title": title, - "Sound": sound, - "Action": action, - "Data": serialize.object(data), - "Apn": serialize.object(apn), - "Gcm": serialize.object(gcm), - "Sms": serialize.object(sms), - "FacebookMessenger": serialize.object(facebook_messenger), - "Fcm": serialize.object(fcm), - "Segment": serialize.map(segment, lambda e: e), - "Alexa": serialize.object(alexa), - "ToBinding": serialize.map(to_binding, lambda e: e), - "DeliveryCallbackUrl": delivery_callback_url, - "Identity": serialize.map(identity, lambda e: e), - "Tag": serialize.map(tag, lambda e: e), - } + 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"] ) - payload = await self._version.create_async( - method="POST", - uri=self._uri, + 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, ) - - return NotificationInstance( + 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: """ diff --git a/twilio/rest/numbers/NumbersBase.py b/twilio/rest/numbers/NumbersBase.py index db8cb4b5d6..d7b4b3ee8e 100644 --- a/twilio/rest/numbers/NumbersBase.py +++ b/twilio/rest/numbers/NumbersBase.py @@ -13,10 +13,13 @@ from twilio.base.domain import Domain 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): + def __init__(self, twilio: Client): """ Initialize the Numbers Domain @@ -24,7 +27,18 @@ def __init__(self, twilio: Client): :returns: Domain for Numbers """ 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: + """ + :returns: Versions v1 of Numbers + """ + if self._v1 is None: + self._v1 = V1(self) + return self._v1 @property def v2(self) -> V2: @@ -35,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 new file mode 100644 index 0000000000..a3f3cc0847 --- /dev/null +++ b/twilio/rest/numbers/v1/__init__.py @@ -0,0 +1,158 @@ +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.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, +) +from twilio.rest.numbers.v1.porting_portability import PortingPortabilityList +from twilio.rest.numbers.v1.porting_webhook_configuration import ( + PortingWebhookConfigurationList, +) +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, +) +from twilio.rest.numbers.v1.webhook import WebhookList + + +class V1(Version): + + def __init__(self, domain: Domain): + """ + Initialize the V1 version of Numbers + + :param domain: The Twilio.numbers 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 + ) + self._porting_portabilities: Optional[PortingPortabilityList] = None + self._porting_webhook_configurations: Optional[ + PortingWebhookConfigurationList + ] = None + self._porting_webhook_configurations_delete: Optional[ + PortingWebhookConfigurationDeleteList + ] = None + self._sender_id_registrations: Optional[SenderIdRegistrationList] = None + self._signing_request_configurations: Optional[ + SigningRequestConfigurationList + ] = None + self._webhook: Optional[WebhookList] = None + + @property + def bulk_eligibilities(self) -> BulkEligibilityList: + if self._bulk_eligibilities is None: + self._bulk_eligibilities = BulkEligibilityList(self) + return self._bulk_eligibilities + + @property + def eligibilities(self) -> EligibilityList: + if self._eligibilities is None: + 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: + self._porting_port_ins = PortingPortInList(self) + return self._porting_port_ins + + @property + def porting_port_in_phone_number(self) -> PortingPortInPhoneNumberList: + if self._porting_port_in_phone_number is None: + self._porting_port_in_phone_number = PortingPortInPhoneNumberList(self) + return self._porting_port_in_phone_number + + @property + def porting_portabilities(self) -> PortingPortabilityList: + if self._porting_portabilities is None: + self._porting_portabilities = PortingPortabilityList(self) + return self._porting_portabilities + + @property + def porting_webhook_configurations(self) -> PortingWebhookConfigurationList: + if self._porting_webhook_configurations is None: + self._porting_webhook_configurations = PortingWebhookConfigurationList(self) + return self._porting_webhook_configurations + + @property + def porting_webhook_configurations_delete( + self, + ) -> PortingWebhookConfigurationDeleteList: + if self._porting_webhook_configurations_delete is None: + self._porting_webhook_configurations_delete = ( + PortingWebhookConfigurationDeleteList(self) + ) + 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: + self._signing_request_configurations = SigningRequestConfigurationList(self) + return self._signing_request_configurations + + @property + def webhook(self) -> WebhookList: + if self._webhook is None: + self._webhook = WebhookList(self) + return self._webhook + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v1/bulk_eligibility.py b/twilio/rest/numbers/v1/bulk_eligibility.py new file mode 100644 index 0000000000..ed521218a5 --- /dev/null +++ b/twilio/rest/numbers/v1/bulk_eligibility.py @@ -0,0 +1,369 @@ +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 +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 BulkEligibilityInstance(InstanceResource): + """ + :ivar request_id: The SID of the bulk eligibility check that you want to know about. + :ivar url: This is the url of the request that you're trying to reach out to locate the resource. + :ivar results: The result set that contains the eligibility check response for each requested number, each result has at least the following attributes: phone_number: The requested phone number ,hosting_account_sid: The account sid where the phone number will be hosted, country: Phone number’s country, eligibility_status: Indicates the eligibility status of the PN (Eligible/Ineligible), eligibility_sub_status: Indicates the sub status of the eligibility , ineligibility_reason: Reason for number's ineligibility (if applicable), next_step: Suggested next step in the hosting process based on the eligibility status. + :ivar friendly_name: This is the string that you assigned as a friendly name for describing the eligibility check request. + :ivar status: This is the status of the bulk eligibility check request. (Example: COMPLETE, IN_PROGRESS) + :ivar date_created: + :ivar date_completed: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + request_id: Optional[str] = None, + ): + super().__init__(version) + + self.request_id: Optional[str] = payload.get("request_id") + self.url: Optional[str] = payload.get("url") + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional[str] = payload.get("status") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + + self._solution = { + "request_id": request_id or self.request_id, + } + + self._context: Optional[BulkEligibilityContext] = None + + @property + def _proxy(self) -> "BulkEligibilityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BulkEligibilityContext for this BulkEligibilityInstance + """ + if self._context is None: + self._context = BulkEligibilityContext( + self._version, + request_id=self._solution["request_id"], + ) + return self._context + + def fetch(self) -> "BulkEligibilityInstance": + """ + Fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "BulkEligibilityInstance": + """ + Asynchronous coroutine to fetch the BulkEligibilityInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BulkEligibilityContext(InstanceContext): + + def __init__(self, version: Version, request_id: str): + """ + Initialize the BulkEligibilityContext + + :param version: Version that contains the resource + :param request_id: The SID of the bulk eligibility check that you want to know about. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "request_id": request_id, + } + self._uri = "/HostedNumber/Eligibility/Bulk/{request_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) -> BulkEligibilityInstance: + """ + Fetch the BulkEligibilityInstance + + + :returns: The fetched BulkEligibilityInstance + """ + payload, _, _ = self._fetch() + return BulkEligibilityInstance( + self._version, + payload, + request_id=self._solution["request_id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BulkEligibilityInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BulkEligibilityList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkEligibilityList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Eligibility/Bulk" + + 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 + ) -> 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"}) + + 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 + ) -> 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 + + :param request_id: The SID of the bulk eligibility check that you want to know about. + """ + return BulkEligibilityContext(self._version, request_id=request_id) + + def __call__(self, request_id: str) -> BulkEligibilityContext: + """ + Constructs a BulkEligibilityContext + + :param request_id: The SID of the bulk eligibility check that you want to know about. + """ + return BulkEligibilityContext(self._version, request_id=request_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v1/eligibility.py b/twilio/rest/numbers/v1/eligibility.py new file mode 100644 index 0000000000..37d6f1c07d --- /dev/null +++ b/twilio/rest/numbers/v1/eligibility.py @@ -0,0 +1,153 @@ +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 +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 EligibilityInstance(InstanceResource): + """ + :ivar results: The result set that contains the eligibility check response for the requested number, each result has at least the following attributes: phone_number: The requested phone number ,hosting_account_sid: The account sid where the phone number will be hosted, date_last_checked: Datetime (ISO 8601) when the PN was last checked for eligibility, country: Phone number’s country, eligibility_status: Indicates the eligibility status of the PN (Eligible/Ineligible), eligibility_sub_status: Indicates the sub status of the eligibility , ineligibility_reason: Reason for number's ineligibility (if applicable), next_step: Suggested next step in the hosting process based on the eligibility status. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class EligibilityList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the EligibilityList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Eligibility" + + 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) -> EligibilityInstance: + """ + Create the EligibilityInstance + + :param body: + + :returns: The created EligibilityInstance + """ + payload, _, _ = self._create(body=body) + return EligibilityInstance(self._version, payload) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the EligibilityInstance and return response metadata + + :param body: + + :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() + + 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 + ) -> 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 + + :returns: Machine friendly representation + """ + return "" 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 "".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 "" 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 "" + + +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 "" + + +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 "" diff --git a/twilio/rest/numbers/v1/porting_port_in.py b/twilio/rest/numbers/v1/porting_port_in.py new file mode 100644 index 0000000000..53400a5fd0 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_port_in.py @@ -0,0 +1,1047 @@ +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 date, 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 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. 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 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 support_ticket_id: Unique ID of the request's support ticket + :ivar signature_request_url: + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + port_in_request_sid: Optional[str] = None, + ): + super().__init__(version) + + self.port_in_request_sid: Optional[str] = payload.get("port_in_request_sid") + self.url: Optional[str] = payload.get("url") + self.account_sid: Optional[str] = payload.get("account_sid") + self.notification_emails: Optional[List[str]] = payload.get( + "notification_emails" + ) + self.target_port_in_date: Optional[date] = deserialize.iso8601_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.port_in_request_status: Optional[str] = payload.get( + "port_in_request_status" + ) + 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[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 + def _proxy(self) -> "PortingPortInContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PortingPortInContext for this PortingPortInInstance + """ + if self._context is None: + self._context = PortingPortInContext( + self._version, + port_in_request_sid=self._solution["port_in_request_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched PortingPortInInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PortingPortInInstance": + """ + Asynchronous coroutine to fetch the PortingPortInInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +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 + + :param version: Version that contains the resource + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "port_in_request_sid": port_in_request_sid, + } + 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 + + + :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 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 PortingPortInInstance + + + :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 PortingPortInInstance 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) -> 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"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +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 + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/PortIn" + + def _create( + self, numbers_v1_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> tuple: + """ + Internal 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"}) + + 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_porting_port_in_create: NumbersV1PortingPortInCreate + ) -> PortingPortInInstance: + """ + Create the PortingPortInInstance + + :param numbers_v1_porting_port_in_create: + + :returns: The created PortingPortInInstance + """ + 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"}) + + 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_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 + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + """ + return PortingPortInContext( + self._version, port_in_request_sid=port_in_request_sid + ) + + def __call__(self, port_in_request_sid: str) -> PortingPortInContext: + """ + Constructs a PortingPortInContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + """ + return PortingPortInContext( + self._version, port_in_request_sid=port_in_request_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v1/porting_port_in_phone_number.py b/twilio/rest/numbers/v1/porting_port_in_phone_number.py new file mode 100644 index 0000000000..1efa19ebe8 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_port_in_phone_number.py @@ -0,0 +1,440 @@ +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_context import InstanceContext +from twilio.base.instance_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + + +class PortingPortInPhoneNumberInstance(InstanceResource): + """ + :ivar port_in_request_sid: The unique identifier for the port in request that this phone number is associated with. + :ivar phone_number_sid: The unique identifier for this phone number associated with this port in request. + :ivar url: URL reference for this resource. + :ivar account_sid: Account Sid or subaccount where the phone number(s) will be Ported. + :ivar phone_number_type: The number type of the phone number. This can be: toll-free, local, mobile or unknown. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + :ivar date_created: The timestamp for when this port in phone number was created. + :ivar country: The ISO country code that this number is associated with. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + :ivar missing_required_fields: Indicates if the phone number is missing required fields such as a PIN or account number. This field may be null if the number is not portable or if the portability for a number has not yet been evaluated. + :ivar last_updated: Timestamp indicating when the Port In Phone Number resource was last modified. + :ivar phone_number: Phone number to be ported. This will be in the E164 Format. + :ivar portable: If the number is portable by Twilio or not. This field may be null if the number portability has not yet been evaluated. If a number is not portable reference the `not_portability_reason_code` and `not_portability_reason` fields for more details + :ivar not_portability_reason: The not portability reason code description. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + :ivar not_portability_reason_code: The not portability reason code. This field may be null if the number is portable or if the portability for a number has not yet been evaluated. + :ivar port_in_phone_number_status: The status of the port in phone number. + :ivar port_out_pin: The pin required by the losing carrier to do the port out. + :ivar rejection_reason: The description of the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + :ivar rejection_reason_code: The code for the rejection reason provided by the losing carrier. This field may be null if the number has not been rejected by the losing carrier. + :ivar port_date: The timestamp the phone number will be ported. This will only be set once a port date has been confirmed. Not all carriers can guarantee a specific time on the port date. Twilio will try its best to get the port completed by this time on the port date. Please subscribe to webhooks for confirmation on when a port has actually been completed. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + port_in_request_sid: Optional[str] = None, + phone_number_sid: Optional[str] = None, + ): + super().__init__(version) + + self.port_in_request_sid: Optional[str] = payload.get("port_in_request_sid") + self.phone_number_sid: Optional[str] = payload.get("phone_number_sid") + self.url: Optional[str] = payload.get("url") + self.account_sid: Optional[str] = payload.get("account_sid") + self.phone_number_type: Optional[str] = payload.get("phone_number_type") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.country: Optional[str] = payload.get("country") + self.missing_required_fields: Optional[bool] = payload.get( + "missing_required_fields" + ) + self.last_updated: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("last_updated") + ) + self.phone_number: Optional[str] = payload.get("phone_number") + self.portable: Optional[bool] = payload.get("portable") + self.not_portability_reason: Optional[str] = payload.get( + "not_portability_reason" + ) + self.not_portability_reason_code: Optional[int] = deserialize.integer( + payload.get("not_portability_reason_code") + ) + self.port_in_phone_number_status: Optional[str] = payload.get( + "port_in_phone_number_status" + ) + self.port_out_pin: Optional[int] = deserialize.integer( + payload.get("port_out_pin") + ) + self.rejection_reason: Optional[str] = payload.get("rejection_reason") + self.rejection_reason_code: Optional[int] = deserialize.integer( + payload.get("rejection_reason_code") + ) + self.port_date: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("port_date") + ) + + self._solution = { + "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 + def _proxy(self) -> "PortingPortInPhoneNumberContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PortingPortInPhoneNumberContext for this PortingPortInPhoneNumberInstance + """ + if self._context is None: + self._context = PortingPortInPhoneNumberContext( + self._version, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the PortingPortInPhoneNumberInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "PortingPortInPhoneNumberInstance": + """ + Asynchronous coroutine to fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortInPhoneNumberContext(InstanceContext): + + def __init__( + self, version: Version, port_in_request_sid: str, phone_number_sid: str + ): + """ + Initialize the PortingPortInPhoneNumberContext + + :param version: Version that contains the resource + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :param phone_number_sid: The SID of the Phone number. This is a unique identifier of the phone number. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "port_in_request_sid": port_in_request_sid, + "phone_number_sid": phone_number_sid, + } + self._uri = "/Porting/PortIn/{port_in_request_sid}/PhoneNumber/{phone_number_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 PortingPortInPhoneNumberInstance + + + :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 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 PortingPortInPhoneNumberInstance + + + :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 PortingPortInPhoneNumberInstance 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) -> PortingPortInPhoneNumberInstance: + """ + Fetch the PortingPortInPhoneNumberInstance + + + :returns: The fetched PortingPortInPhoneNumberInstance + """ + payload, _, _ = self._fetch() + return PortingPortInPhoneNumberInstance( + self._version, + payload, + port_in_request_sid=self._solution["port_in_request_sid"], + phone_number_sid=self._solution["phone_number_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PortingPortInPhoneNumberInstance and return response metadata + + + :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" + + 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, + port_in_request_sid=self._solution["port_in_request_sid"], + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortInPhoneNumberList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingPortInPhoneNumberList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, port_in_request_sid: str, phone_number_sid: str + ) -> PortingPortInPhoneNumberContext: + """ + Constructs a PortingPortInPhoneNumberContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :param phone_number_sid: The SID of the Phone number. This is a unique identifier of the phone number. + """ + return PortingPortInPhoneNumberContext( + self._version, + port_in_request_sid=port_in_request_sid, + phone_number_sid=phone_number_sid, + ) + + def __call__( + self, port_in_request_sid: str, phone_number_sid: str + ) -> PortingPortInPhoneNumberContext: + """ + Constructs a PortingPortInPhoneNumberContext + + :param port_in_request_sid: The SID of the Port In request. This is a unique identifier of the port in request. + :param phone_number_sid: The SID of the Phone number. This is a unique identifier of the phone number. + """ + return PortingPortInPhoneNumberContext( + self._version, + port_in_request_sid=port_in_request_sid, + phone_number_sid=phone_number_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v1/porting_portability.py b/twilio/rest/numbers/v1/porting_portability.py new file mode 100644 index 0000000000..5bcc0e604c --- /dev/null +++ b/twilio/rest/numbers/v1/porting_portability.py @@ -0,0 +1,377 @@ +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, 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 PortingPortabilityInstance(InstanceResource): + + class NumberType(object): + LOCAL = "LOCAL" + UNKNOWN = "UNKNOWN" + MOBILE = "MOBILE" + TOLL_FREE = "TOLL-FREE" + + """ + :ivar phone_number: The phone number which portability is to be checked. Phone numbers are in E.164 format (e.g. +16175551212). + :ivar account_sid: Account Sid that the phone number belongs to in Twilio. This is only returned for phone numbers that already exist in Twilio’s inventory and belong to your account or sub account. + :ivar portable: Boolean flag indicates if the phone number can be ported into Twilio through the Porting API or not. + :ivar pin_and_account_number_required: Indicates if the port in process will require a personal identification number (PIN) and an account number for this phone number. If this is true you will be required to submit both a PIN and account number from the losing carrier for this number when opening a port in request. These fields will be required in order to complete the port in process to Twilio. + :ivar not_portable_reason: Reason why the phone number cannot be ported into Twilio, `null` otherwise. + :ivar not_portable_reason_code: The Portability Reason Code for the phone number if it cannot be ported into Twilio, `null` otherwise. + :ivar number_type: + :ivar country: Country the phone number belongs to. + :ivar url: This is the url of the request that you're trying to reach out to locate the resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + phone_number: Optional[str] = None, + ): + super().__init__(version) + + self.phone_number: Optional[str] = payload.get("phone_number") + self.account_sid: Optional[str] = payload.get("account_sid") + self.portable: Optional[bool] = payload.get("portable") + self.pin_and_account_number_required: Optional[bool] = payload.get( + "pin_and_account_number_required" + ) + self.not_portable_reason: Optional[str] = payload.get("not_portable_reason") + self.not_portable_reason_code: Optional[int] = deserialize.integer( + payload.get("not_portable_reason_code") + ) + self.number_type: Optional["PortingPortabilityInstance.NumberType"] = ( + payload.get("number_type") + ) + self.country: Optional[str] = payload.get("country") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "phone_number": phone_number or self.phone_number, + } + + self._context: Optional[PortingPortabilityContext] = None + + @property + def _proxy(self) -> "PortingPortabilityContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: PortingPortabilityContext for this PortingPortabilityInstance + """ + if self._context is None: + self._context = PortingPortabilityContext( + self._version, + phone_number=self._solution["phone_number"], + ) + return self._context + + 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 + """ + return self._proxy.fetch( + target_account_sid=target_account_sid, + address_sid=address_sid, + ) + + 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 + """ + return await self._proxy.fetch_async( + target_account_sid=target_account_sid, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortabilityContext(InstanceContext): + + def __init__(self, version: Version, phone_number: str): + """ + Initialize the PortingPortabilityContext + + :param version: Version that contains the resource + :param phone_number: Phone number to check portability in e164 format. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "phone_number": phone_number, + } + self._uri = "/Porting/Portability/PhoneNumber/{phone_number}".format( + **self._solution + ) + + def _fetch( + self, + target_account_sid: Union[str, object] = values.unset, + address_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "TargetAccountSid": target_account_sid, + "AddressSid": address_sid, + } + ) + + 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, + 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"], + ) + + 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 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 = 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) + + 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, + } + ) + + 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, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class PortingPortabilityList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingPortabilityList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, phone_number: str) -> PortingPortabilityContext: + """ + Constructs a PortingPortabilityContext + + :param phone_number: Phone number to check portability in e164 format. + """ + return PortingPortabilityContext(self._version, phone_number=phone_number) + + def __call__(self, phone_number: str) -> PortingPortabilityContext: + """ + Constructs a PortingPortabilityContext + + :param phone_number: Phone number to check portability in e164 format. + """ + return PortingPortabilityContext(self._version, phone_number=phone_number) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v1/porting_webhook_configuration.py b/twilio/rest/numbers/v1/porting_webhook_configuration.py new file mode 100644 index 0000000000..4769c6ae74 --- /dev/null +++ b/twilio/rest/numbers/v1/porting_webhook_configuration.py @@ -0,0 +1,161 @@ +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 +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 PortingWebhookConfigurationInstance(InstanceResource): + """ + :ivar url: The URL of the webhook configuration request + :ivar port_in_target_url: The complete webhook url that will be called when a notification event for port in request or port in phone number happens + :ivar port_out_target_url: The complete webhook url that will be called when a notification event for a port out phone number happens. + :ivar notifications_of: A list to filter what notification events to receive for this account and its sub accounts. If it is an empty list, then it means that there are no filters for the notifications events to send in each webhook and all events will get sent. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.port_in_target_url: Optional[str] = payload.get("port_in_target_url") + self.port_out_target_url: Optional[str] = payload.get("port_out_target_url") + self.notifications_of: Optional[List[str]] = payload.get("notifications_of") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class PortingWebhookConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingWebhookConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/Configuration/Webhook" + + 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 + ) -> 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"}) + + 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 + ) -> 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py b/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py new file mode 100644 index 0000000000..e724498b0a --- /dev/null +++ b/twilio/rest/numbers/v1/porting_webhook_configuration_delete.py @@ -0,0 +1,167 @@ +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 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 +from twilio.base.version import Version + + +class PortingWebhookConfigurationDeleteContext(InstanceContext): + + def __init__( + self, + version: Version, + webhook_type: "PortingWebhookConfigurationDeleteInstance.WebhookType", + ): + """ + Initialize the PortingWebhookConfigurationDeleteContext + + :param version: Version that contains the resource + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` + """ + super().__init__(version) + + # Path Solution + self._solution = { + "webhook_type": webhook_type, + } + self._uri = "/Porting/Configuration/Webhook/{webhook_type}".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 PortingWebhookConfigurationDeleteInstance + + + :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 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 PortingWebhookConfigurationDeleteInstance + + + :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 PortingWebhookConfigurationDeleteInstance 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 __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 PortingWebhookConfigurationDeleteList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the PortingWebhookConfigurationDeleteList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get( + self, webhook_type: "PortingWebhookConfigurationDeleteInstance.WebhookType" + ) -> PortingWebhookConfigurationDeleteContext: + """ + Constructs a PortingWebhookConfigurationDeleteContext + + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` + """ + return PortingWebhookConfigurationDeleteContext( + self._version, webhook_type=webhook_type + ) + + def __call__( + self, webhook_type: "PortingWebhookConfigurationDeleteInstance.WebhookType" + ) -> PortingWebhookConfigurationDeleteContext: + """ + Constructs a PortingWebhookConfigurationDeleteContext + + :param webhook_type: The webhook type for the configuration to be delete. `PORT_IN`, `PORT_OUT` + """ + return PortingWebhookConfigurationDeleteContext( + self._version, webhook_type=webhook_type + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" 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 "" + + +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 "" diff --git a/twilio/rest/numbers/v1/signing_request_configuration.py b/twilio/rest/numbers/v1/signing_request_configuration.py new file mode 100644 index 0000000000..18e6f97003 --- /dev/null +++ b/twilio/rest/numbers/v1/signing_request_configuration.py @@ -0,0 +1,627 @@ +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 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 SigningRequestConfigurationInstance(InstanceResource): + """ + :ivar logo_sid: The SID of the document that includes the logo that will appear in the LOA. To upload documents follow the following guide: https://www.twilio.com/docs/phone-numbers/regulatory/getting-started/create-new-bundle-public-rest-apis#supporting-document-create + :ivar friendly_name: This is the string that you assigned as a friendly name for describing the creation of the configuration. + :ivar product: The product or service for which is requesting the signature. + :ivar country: The country ISO code to apply the configuration. + :ivar email_subject: Subject of the email that the end client will receive ex: “Twilio Hosting Request”, maximum length of 255 characters. + :ivar email_message: Content of the email that the end client will receive ex: “This is a Hosting request from Twilio, please check the document and sign it”, maximum length of 5,000 characters. + :ivar url_redirection: Url the end client will be redirected after signing a document. + :ivar url: + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.logo_sid: Optional[str] = payload.get("logo_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.product: Optional[str] = payload.get("product") + self.country: Optional[str] = payload.get("country") + self.email_subject: Optional[str] = payload.get("email_subject") + self.email_message: Optional[str] = payload.get("email_message") + self.url_redirection: Optional[str] = payload.get("url_redirection") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class SigningRequestConfigurationPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> SigningRequestConfigurationInstance: + """ + Build an instance of SigningRequestConfigurationInstance + + :param payload: Payload response from the API + """ + + return SigningRequestConfigurationInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class SigningRequestConfigurationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the SigningRequestConfigurationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/SigningRequest/Configuration" + + 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 + ) -> 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"}) + + 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 + ) -> 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, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[SigningRequestConfigurationInstance]: + """ + Streams SigningRequestConfigurationInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + country=country, product=product, page_size=limits["page_size"] + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[SigningRequestConfigurationInstance]: + """ + Asynchronously streams SigningRequestConfigurationInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + country=country, product=product, page_size=limits["page_size"] + ) + + 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, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningRequestConfigurationInstance]: + """ + Lists SigningRequestConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + country: Union[str, object] = values.unset, + product: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[SigningRequestConfigurationInstance]: + """ + Asynchronously lists SigningRequestConfigurationInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + country=country, + product=product, + limit=limit, + page_size=page_size, + ) + ] + + 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, + 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, + ) -> SigningRequestConfigurationPage: + """ + Retrieve a single page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :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: Page of SigningRequestConfigurationInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return SigningRequestConfigurationPage(self._version, response) + + async def page_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, + ) -> SigningRequestConfigurationPage: + """ + Asynchronously retrieve a single page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :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: Page of SigningRequestConfigurationInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningRequestConfigurationInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return SigningRequestConfigurationPage(self._version, response) + + async def get_page_async(self, target_url: str) -> SigningRequestConfigurationPage: + """ + Asynchronously retrieve a specific page of SigningRequestConfigurationInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of SigningRequestConfigurationInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return SigningRequestConfigurationPage(self._version, response) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v1/webhook.py b/twilio/rest/numbers/v1/webhook.py new file mode 100644 index 0000000000..c5c9783f7f --- /dev/null +++ b/twilio/rest/numbers/v1/webhook.py @@ -0,0 +1,150 @@ +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 +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 WebhookInstance(InstanceResource): + """ + :ivar url: The URL of the webhook configuration request + :ivar port_in_target_url: The complete webhook url that will be called when a notification event for port in request or port in phone number happens + :ivar port_out_target_url: The complete webhook url that will be called when a notification event for a port out phone number happens. + :ivar notifications_of: A list to filter what notification events to receive for this account and its sub accounts. If it is an empty list, then it means that there are no filters for the notifications events to send in each webhook and all events will get sent. + :ivar port_in_target_date_created: Creation date for the port in webhook configuration + :ivar port_out_target_date_created: Creation date for the port out webhook configuration + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.url: Optional[str] = payload.get("url") + self.port_in_target_url: Optional[str] = payload.get("port_in_target_url") + self.port_out_target_url: Optional[str] = payload.get("port_out_target_url") + self.notifications_of: Optional[List[str]] = payload.get("notifications_of") + self.port_in_target_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("port_in_target_date_created")) + ) + self.port_out_target_date_created: Optional[datetime] = ( + deserialize.iso8601_datetime(payload.get("port_out_target_date_created")) + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class WebhookList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the WebhookList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/Porting/Configuration/Webhook" + + 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) -> WebhookInstance: + """ + Fetch the WebhookInstance + + + :returns: The fetched WebhookInstance + """ + payload, _, _ = self._fetch() + return WebhookInstance(self._version, payload) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :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" + + 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v2/__init__.py b/twilio/rest/numbers/v2/__init__.py index bf3dc53ba2..e4f3060250 100644 --- a/twilio/rest/numbers/v2/__init__.py +++ b/twilio/rest/numbers/v2/__init__.py @@ -15,10 +15,16 @@ 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 +from twilio.rest.numbers.v2.hosted_number_order import HostedNumberOrderList from twilio.rest.numbers.v2.regulatory_compliance import RegulatoryComplianceList class V2(Version): + def __init__(self, domain: Domain): """ Initialize the V2 version of Numbers @@ -26,8 +32,43 @@ 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: + self._authorization_documents = AuthorizationDocumentList(self) + return self._authorization_documents + + @property + def bulk_hosted_number_orders(self) -> BulkHostedNumberOrderList: + if self._bulk_hosted_number_orders is None: + self._bulk_hosted_number_orders = BulkHostedNumberOrderList(self) + return self._bulk_hosted_number_orders + + @property + def bundle_clone(self) -> BundleCloneList: + if self._bundle_clone is None: + self._bundle_clone = BundleCloneList(self) + return self._bundle_clone + + @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 + @property def regulatory_compliance(self) -> RegulatoryComplianceList: if self._regulatory_compliance 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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/numbers/v2/authorization_document/__init__.py b/twilio/rest/numbers/v2/authorization_document/__init__.py new file mode 100644 index 0000000000..8956774fa8 --- /dev/null +++ b/twilio/rest/numbers/v2/authorization_document/__init__.py @@ -0,0 +1,1074 @@ +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, 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.numbers.v2.authorization_document.dependent_hosted_number_order import ( + DependentHostedNumberOrderList, +) + + +class AuthorizationDocumentInstance(InstanceResource): + + class Status(object): + OPENED = "opened" + SIGNING = "signing" + SIGNED = "signed" + CANCELED = "canceled" + FAILED = "failed" + + """ + :ivar sid: A 34 character string that uniquely identifies this AuthorizationDocument. + :ivar address_sid: A 34 character string that uniquely identifies the Address resource that is associated with this AuthorizationDocument. + :ivar status: + :ivar email: Email that this AuthorizationDocument will be sent to for signing. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed. + :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 url: + :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.address_sid: Optional[str] = payload.get("address_sid") + self.status: Optional["AuthorizationDocumentInstance.Status"] = payload.get( + "status" + ) + self.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + 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[AuthorizationDocumentContext] = None + + @property + def _proxy(self) -> "AuthorizationDocumentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AuthorizationDocumentContext for this AuthorizationDocumentInstance + """ + if self._context is None: + self._context = AuthorizationDocumentContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the AuthorizationDocumentInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched AuthorizationDocumentInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AuthorizationDocumentInstance": + """ + Asynchronous coroutine to fetch the AuthorizationDocumentInstance + + + :returns: The fetched 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: + """ + Access the dependent_hosted_number_orders + """ + return self._proxy.dependent_hosted_number_orders + + 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 AuthorizationDocumentContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the AuthorizationDocumentContext + + :param version: Version that contains the resource + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + self._uri = "/HostedNumber/AuthorizationDocuments/{sid}".format( + **self._solution + ) + + self._dependent_hosted_number_orders: Optional[ + 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 + + + :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 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 AuthorizationDocumentInstance + + + :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 AuthorizationDocumentInstance 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) -> AuthorizationDocumentInstance: + """ + Fetch the AuthorizationDocumentInstance + + + :returns: The fetched AuthorizationDocumentInstance + """ + payload, _, _ = self._fetch() + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizationDocumentInstance and return response metadata + + + :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" + + 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: + """ + Access the dependent_hosted_number_orders + """ + if self._dependent_hosted_number_orders is None: + self._dependent_hosted_number_orders = DependentHostedNumberOrderList( + self._version, + self._solution["sid"], + ) + return self._dependent_hosted_number_orders + + 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 AuthorizationDocumentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance: + """ + Build an instance of AuthorizationDocumentInstance + + :param payload: Payload response from the API + """ + + return AuthorizationDocumentInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AuthorizationDocumentList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the AuthorizationDocumentList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/AuthorizationDocuments" + + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AddressSid": address_sid, + "Email": email, + "ContactPhoneNumber": contact_phone_number, + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "ContactTitle": contact_title, + "CcEmails": serialize.map(cc_emails, lambda e: 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.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + 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: + """ + 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, _, _ = 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( + { + "AddressSid": address_sid, + "Email": email, + "ContactPhoneNumber": contact_phone_number, + "HostedNumberOrderSids": serialize.map( + hosted_number_order_sids, lambda e: e + ), + "ContactTitle": contact_title, + "CcEmails": serialize.map(cc_emails, lambda e: 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.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, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AuthorizationDocumentInstance]: + """ + Streams AuthorizationDocumentInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(email=email, status=status, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[AuthorizationDocumentInstance]: + """ + Asynchronously streams AuthorizationDocumentInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + email=email, status=status, page_size=limits["page_size"] + ) + + 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, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + email: Union[str, object] = values.unset, + status: Union["AuthorizationDocumentInstance.Status", object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[AuthorizationDocumentInstance]: + """ + Asynchronously lists AuthorizationDocumentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + email=email, + status=status, + limit=limit, + page_size=page_size, + ) + ] + + 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, + 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, + ) -> AuthorizationDocumentPage: + """ + Retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :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: Page of AuthorizationDocumentInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return AuthorizationDocumentPage(self._version, response) + + async def page_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, + ) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a single page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :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: Page of AuthorizationDocumentInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + async def get_page_async(self, target_url: str) -> AuthorizationDocumentPage: + """ + Asynchronously retrieve a specific page of AuthorizationDocumentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AuthorizationDocumentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AuthorizationDocumentPage(self._version, response) + + def get(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __call__(self, sid: str) -> AuthorizationDocumentContext: + """ + Constructs a AuthorizationDocumentContext + + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. + """ + return AuthorizationDocumentContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" 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 new file mode 100644 index 0000000000..eed80d038f --- /dev/null +++ b/twilio/rest/numbers/v2/authorization_document/dependent_hosted_number_order.py @@ -0,0 +1,711 @@ +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_resource import InstanceResource +from twilio.base.list_resource import ListResource +from twilio.base.version import Version +from twilio.base.page import Page + + +class DependentHostedNumberOrderInstance(InstanceResource): + + class Status(object): + RECEIVED = "received" + VERIFIED = "verified" + PENDING_LOA = "pending-loa" + CARRIER_PROCESSING = "carrier-processing" + COMPLETED = "completed" + FAILED = "failed" + ACTION_REQUIRED = "action-required" + + """ + :ivar sid: A 34 character string that uniquely identifies this Authorization Document + :ivar bulk_hosting_request_sid: A 34 character string that uniquely identifies the bulk hosting request associated with this HostedNumberOrder. + :ivar next_step: The next step you need to take to complete the hosted number order and request it successfully. + :ivar account_sid: The unique SID identifier of the Account. + :ivar incoming_phone_number_sid: A 34 character string that uniquely identifies the IncomingPhoneNumber resource created by this HostedNumberOrder. + :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 LOA document associated with this HostedNumberOrder. + :ivar phone_number: An E164 formatted phone number hosted by this HostedNumberOrder. + :ivar capabilities: + :ivar friendly_name: A human readable description of this resource, up to 128 characters. + :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 email: Email of the owner of this phone number that is being hosted. + :ivar cc_emails: Email recipients who will be informed when an Authorization Document has been sent and signed + :ivar contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :ivar contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + """ + + def __init__( + self, version: Version, payload: Dict[str, Any], signing_document_sid: str + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + self.bulk_hosting_request_sid: Optional[str] = payload.get( + "bulk_hosting_request_sid" + ) + self.next_step: Optional[str] = payload.get("next_step") + self.account_sid: Optional[str] = payload.get("account_sid") + self.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["DependentHostedNumberOrderInstance.Status"] = ( + payload.get("status") + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + 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.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.contact_title: Optional[str] = payload.get("contact_title") + self.contact_phone_number: Optional[str] = payload.get("contact_phone_number") + + self._solution = { + "signing_document_sid": signing_document_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 DependentHostedNumberOrderPage(Page): + + def get_instance( + self, payload: Dict[str, Any] + ) -> DependentHostedNumberOrderInstance: + """ + Build an instance of DependentHostedNumberOrderInstance + + :param payload: Payload response from the API + """ + + return DependentHostedNumberOrderInstance( + self._version, + payload, + signing_document_sid=self._solution["signing_document_sid"], + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class DependentHostedNumberOrderList(ListResource): + + def __init__(self, version: Version, signing_document_sid: str): + """ + Initialize the DependentHostedNumberOrderList + + :param version: Version that contains the resource + :param signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "signing_document_sid": signing_document_sid, + } + self._uri = "/HostedNumber/AuthorizationDocuments/{signing_document_sid}/DependentHostedNumberOrders".format( + **self._solution + ) + + def stream( + 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, + ) -> Iterator[DependentHostedNumberOrderInstance]: + """ + Streams DependentHostedNumberOrderInstance 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_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, + ) -> AsyncIterator[DependentHostedNumberOrderInstance]: + """ + Asynchronously streams DependentHostedNumberOrderInstance 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + page_size=limits["page_size"], + ) + + 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[ + "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, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + status=status, + phone_number=phone_number, + incoming_phone_number_sid=incoming_phone_number_sid, + friendly_name=friendly_name, + limit=limit, + page_size=page_size, + ) + ) + + async def list_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, + ) -> List[DependentHostedNumberOrderInstance]: + """ + Asynchronously lists DependentHostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_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, + ) + ] + + 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[ + "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, + ) -> DependentHostedNumberOrderPage: + """ + Retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :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: Page of DependentHostedNumberOrderInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + + async def page_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, + ) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a single page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :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: Page of DependentHostedNumberOrderInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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: + """ + Retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + + async def get_page_async(self, target_url: str) -> DependentHostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of DependentHostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of DependentHostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v2/bulk_hosted_number_order.py b/twilio/rest/numbers/v2/bulk_hosted_number_order.py new file mode 100644 index 0000000000..7ff4f50a40 --- /dev/null +++ b/twilio/rest/numbers/v2/bulk_hosted_number_order.py @@ -0,0 +1,435 @@ +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 +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 BulkHostedNumberOrderInstance(InstanceResource): + + class RequestStatus(object): + QUEUED = "QUEUED" + IN_PROGRESS = "IN_PROGRESS" + PROCESSED = "PROCESSED" + + """ + :ivar bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + :ivar request_status: + :ivar friendly_name: A 128 character string that is a human-readable text that describes this resource. + :ivar notification_email: Email address used for send notifications about this Bulk hosted number request. + :ivar date_created: The date this resource was created, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar date_completed: The date that this resource was completed, given as [GMT RFC 2822](http://www.ietf.org/rfc/rfc2822.txt) format. + :ivar url: The URL of this BulkHostedNumberOrder resource. + :ivar total_count: The total count of phone numbers in this Bulk hosting request. + :ivar results: Contains a list of all the individual hosting orders and their information, for this Bulk request. Each result object is grouped by its order status. To see a complete list of order status, please check 'https://www.twilio.com/docs/phone-numbers/hosted-numbers/hosted-numbers-api/hosted-number-order-resource#status-values'. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bulk_hosting_sid: Optional[str] = None, + ): + super().__init__(version) + + self.bulk_hosting_sid: Optional[str] = payload.get("bulk_hosting_sid") + self.request_status: Optional["BulkHostedNumberOrderInstance.RequestStatus"] = ( + payload.get("request_status") + ) + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.notification_email: Optional[str] = payload.get("notification_email") + self.date_created: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_created") + ) + self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("date_completed") + ) + self.url: Optional[str] = payload.get("url") + self.total_count: Optional[int] = deserialize.integer( + payload.get("total_count") + ) + self.results: Optional[List[Dict[str, object]]] = payload.get("results") + + self._solution = { + "bulk_hosting_sid": bulk_hosting_sid or self.bulk_hosting_sid, + } + + self._context: Optional[BulkHostedNumberOrderContext] = None + + @property + def _proxy(self) -> "BulkHostedNumberOrderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BulkHostedNumberOrderContext for this BulkHostedNumberOrderInstance + """ + if self._context is None: + self._context = BulkHostedNumberOrderContext( + self._version, + bulk_hosting_sid=self._solution["bulk_hosting_sid"], + ) + return self._context + + 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 + """ + return self._proxy.fetch( + order_status=order_status, + ) + + 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 + """ + return await self._proxy.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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BulkHostedNumberOrderContext(InstanceContext): + + def __init__(self, version: Version, bulk_hosting_sid: str): + """ + Initialize the BulkHostedNumberOrderContext + + :param version: Version that contains the resource + :param bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bulk_hosting_sid": bulk_hosting_sid, + } + self._uri = "/HostedNumber/Orders/Bulk/{bulk_hosting_sid}".format( + **self._solution + ) + + def _fetch(self, order_status: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "OrderStatus": order_status, + } + ) + + 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, 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"], + ) + + def fetch_with_http_info( + self, order_status: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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 + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "OrderStatus": order_status, + } + ) + + 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, 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BulkHostedNumberOrderList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BulkHostedNumberOrderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Orders/Bulk" + + 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 + ) -> 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"}) + + 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 + ) -> 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 + + :param bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + """ + return BulkHostedNumberOrderContext( + self._version, bulk_hosting_sid=bulk_hosting_sid + ) + + def __call__(self, bulk_hosting_sid: str) -> BulkHostedNumberOrderContext: + """ + Constructs a BulkHostedNumberOrderContext + + :param bulk_hosting_sid: A 34 character string that uniquely identifies this BulkHostedNumberOrder. + """ + return BulkHostedNumberOrderContext( + self._version, bulk_hosting_sid=bulk_hosting_sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v2/bundle_clone.py b/twilio/rest/numbers/v2/bundle_clone.py new file mode 100644 index 0000000000..7cee570fb3 --- /dev/null +++ b/twilio/rest/numbers/v2/bundle_clone.py @@ -0,0 +1,410 @@ +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, 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 +from twilio.base.version import Version + + +class BundleCloneInstance(InstanceResource): + + class Status(object): + DRAFT = "draft" + PENDING_REVIEW = "pending-review" + IN_REVIEW = "in-review" + TWILIO_REJECTED = "twilio-rejected" + TWILIO_APPROVED = "twilio-approved" + PROVISIONALLY_APPROVED = "provisionally-approved" + + """ + :ivar bundle_sid: The unique string that we created to identify the Bundle resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Bundle resource. + :ivar regulation_sid: The unique string of a regulation that is associated to the Bundle resource. + :ivar friendly_name: The string that you assigned to describe the resource. + :ivar status: + :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 email: The email address that will receive updates when the Bundle resource changes status. + :ivar status_callback: The URL we call to inform your application of status changes. + :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 URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + bundle_sid: Optional[str] = None, + ): + super().__init__(version) + + self.bundle_sid: Optional[str] = payload.get("bundle_sid") + self.account_sid: Optional[str] = payload.get("account_sid") + self.regulation_sid: Optional[str] = payload.get("regulation_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["BundleCloneInstance.Status"] = payload.get("status") + self.valid_until: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("valid_until") + ) + self.email: Optional[str] = payload.get("email") + self.status_callback: Optional[str] = payload.get("status_callback") + 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 = { + "bundle_sid": bundle_sid or self.bundle_sid, + } + + self._context: Optional[BundleCloneContext] = None + + @property + def _proxy(self) -> "BundleCloneContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: BundleCloneContext for this BundleCloneInstance + """ + if self._context is None: + self._context = BundleCloneContext( + self._version, + bundle_sid=self._solution["bundle_sid"], + ) + return self._context + + def create( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "BundleCloneInstance": + """ + Create the BundleCloneInstance + + :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: The created BundleCloneInstance + """ + return self._proxy.create( + target_account_sid, + move_to_draft=move_to_draft, + friendly_name=friendly_name, + ) + + async def create_async( + self, + target_account_sid: str, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> "BundleCloneInstance": + """ + Asynchronous coroutine to create the BundleCloneInstance + + :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: The created BundleCloneInstance + """ + return await self._proxy.create_async( + target_account_sid, + move_to_draft=move_to_draft, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BundleCloneContext(InstanceContext): + + def __init__(self, version: Version, bundle_sid: str): + """ + Initialize the BundleCloneContext + + :param version: Version that contains the resource + :param bundle_sid: The unique string that identifies the Bundle to be cloned. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "bundle_sid": bundle_sid, + } + self._uri = "/RegulatoryCompliance/Bundles/{bundle_sid}/Clones".format( + **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, + move_to_draft: Union[bool, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> BundleCloneInstance: + """ + Create the BundleCloneInstance + + :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: 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, + "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 await self._version.create_with_response_info_async( + method="POST", uri=self._uri, data=data, 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, + ) -> BundleCloneInstance: + """ + Asynchronous coroutine to create the BundleCloneInstance + + :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: The created BundleCloneInstance + """ + payload, _, _ = await self._create_async( + 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"] + ) + + 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: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class BundleCloneList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the BundleCloneList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, bundle_sid: str) -> BundleCloneContext: + """ + Constructs a BundleCloneContext + + :param bundle_sid: The unique string that identifies the Bundle to be cloned. + """ + return BundleCloneContext(self._version, bundle_sid=bundle_sid) + + def __call__(self, bundle_sid: str) -> BundleCloneContext: + """ + Constructs a BundleCloneContext + + :param bundle_sid: The unique string that identifies the Bundle to be cloned. + """ + return BundleCloneContext(self._version, bundle_sid=bundle_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v2/hosted_number_order.py b/twilio/rest/numbers/v2/hosted_number_order.py new file mode 100644 index 0000000000..dce5e77367 --- /dev/null +++ b/twilio/rest/numbers/v2/hosted_number_order.py @@ -0,0 +1,1616 @@ +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, 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 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" + + """ + :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 128 character string that is a human-readable text that describes this resource. + :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 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 contact_title: The title of the person authorized to sign the Authorization Document for this phone number. + :ivar contact_phone_number: The contact phone number of the person authorized to sign the Authorization Document. + :ivar bulk_hosting_request_sid: A 34 character string that uniquely identifies the bulk hosting request associated with this HostedNumberOrder. + :ivar next_step: The next step you need to take to complete the hosted number order and request it successfully. + :ivar verification_attempts: The number of attempts made to verify ownership via a call for the hosted phone number. + :ivar verification_call_sids: The Call SIDs that identify the calls placed to verify ownership. + :ivar verification_call_delay: The number of seconds to wait before initiating the ownership verification call. Can be a value between 0 and 60, inclusive. + :ivar verification_call_extension: The numerical extension to dial when making the ownership verification call. + :ivar verification_code: The digits the user must pass in the ownership verification call. + :ivar verification_type: + """ + + 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.incoming_phone_number_sid: Optional[str] = payload.get( + "incoming_phone_number_sid" + ) + self.address_sid: Optional[str] = payload.get("address_sid") + self.signing_document_sid: Optional[str] = payload.get("signing_document_sid") + self.phone_number: Optional[str] = payload.get("phone_number") + self.capabilities: Optional[str] = payload.get("capabilities") + self.friendly_name: Optional[str] = payload.get("friendly_name") + self.status: Optional["HostedNumberOrderInstance.Status"] = payload.get( + "status" + ) + self.failure_reason: Optional[str] = payload.get("failure_reason") + 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.email: Optional[str] = payload.get("email") + self.cc_emails: Optional[List[str]] = payload.get("cc_emails") + self.url: Optional[str] = payload.get("url") + self.contact_title: Optional[str] = payload.get("contact_title") + self.contact_phone_number: Optional[str] = payload.get("contact_phone_number") + self.bulk_hosting_request_sid: Optional[str] = payload.get( + "bulk_hosting_request_sid" + ) + self.next_step: Optional[str] = payload.get("next_step") + self.verification_attempts: Optional[int] = deserialize.integer( + payload.get("verification_attempts") + ) + self.verification_call_sids: Optional[List[str]] = payload.get( + "verification_call_sids" + ) + self.verification_call_delay: Optional[int] = deserialize.integer( + payload.get("verification_call_delay") + ) + self.verification_call_extension: Optional[str] = payload.get( + "verification_call_extension" + ) + self.verification_code: Optional[str] = payload.get("verification_code") + self.verification_type: Optional[ + "HostedNumberOrderInstance.VerificationType" + ] = payload.get("verification_type") + + self._solution = { + "sid": sid or self.sid, + } + + self._context: Optional[HostedNumberOrderContext] = None + + @property + def _proxy(self) -> "HostedNumberOrderContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: HostedNumberOrderContext for this HostedNumberOrderInstance + """ + if self._context is None: + self._context = HostedNumberOrderContext( + self._version, + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched HostedNumberOrderInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "HostedNumberOrderInstance": + """ + Asynchronous coroutine to fetch the HostedNumberOrderInstance + + + :returns: The fetched 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", + 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 + """ + return self._proxy.update( + status=status, + verification_call_delay=verification_call_delay, + verification_call_extension=verification_call_extension, + ) + + 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 + """ + return await self._proxy.update_async( + status=status, + verification_call_delay=verification_call_delay, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class HostedNumberOrderContext(InstanceContext): + + def __init__(self, version: Version, sid: str): + """ + Initialize the HostedNumberOrderContext + + :param version: Version that contains the resource + :param sid: The SID of the HostedNumberOrder resource to update. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "sid": sid, + } + 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 + + + :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 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 HostedNumberOrderInstance + + + :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 HostedNumberOrderInstance 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) -> HostedNumberOrderInstance: + """ + Fetch the HostedNumberOrderInstance + + + :returns: The fetched HostedNumberOrderInstance + """ + payload, _, _ = self._fetch() + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the HostedNumberOrderInstance and return response metadata + + + :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" + + 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"], + ) + + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "VerificationCallDelay": verification_call_delay, + "VerificationCallExtension": verification_call_extension, + } + ) + 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: "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"] + ) + + 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 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 = 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( + { + "Status": status, + "VerificationCallDelay": verification_call_delay, + "VerificationCallExtension": verification_call_extension, + } + ) + 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: "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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class HostedNumberOrderPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: + """ + Build an instance of HostedNumberOrderInstance + + :param payload: Payload response from the API + """ + + return HostedNumberOrderInstance(self._version, payload) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class HostedNumberOrderList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the HostedNumberOrderList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/HostedNumber/Orders" + + def _create( + 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 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 self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + 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: + """ + 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, _, _ = 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, + ) + return HostedNumberOrderInstance(self._version, payload) + + 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, + 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, + ) -> Iterator[HostedNumberOrderInstance]: + """ + Streams HostedNumberOrderInstance 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page( + 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"], + ) + + return self._version.stream(page, limits["limit"]) + + async def stream_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, + ) -> AsyncIterator[HostedNumberOrderInstance]: + """ + Asynchronously streams HostedNumberOrderInstance 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 "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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_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"], + ) + + 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, + 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, + ) -> List[HostedNumberOrderInstance]: + """ + Lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + 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, + ) + ) + + async def list_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, + ) -> List[HostedNumberOrderInstance]: + """ + Asynchronously lists HostedNumberOrderInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_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, + ) + ] + + 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, + 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, + ) -> HostedNumberOrderPage: + """ + Retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :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: Page of HostedNumberOrderInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return HostedNumberOrderPage(self._version, response) + + async def page_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, + ) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a single page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :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: Page of HostedNumberOrderInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + async def get_page_async(self, target_url: str) -> HostedNumberOrderPage: + """ + Asynchronously retrieve a specific page of HostedNumberOrderInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of HostedNumberOrderInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return HostedNumberOrderPage(self._version, response) + + def get(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: The SID of the HostedNumberOrder resource to update. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __call__(self, sid: str) -> HostedNumberOrderContext: + """ + Constructs a HostedNumberOrderContext + + :param sid: The SID of the HostedNumberOrder resource to update. + """ + return HostedNumberOrderContext(self._version, sid=sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/numbers/v2/regulatory_compliance/__init__.py b/twilio/rest/numbers/v2/regulatory_compliance/__init__.py index 9afca8a972..189117d85c 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/__init__.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -32,6 +31,7 @@ class RegulatoryComplianceList(ListResource): + def __init__(self, version: Version): """ Initialize the RegulatoryComplianceList diff --git a/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py index ff7b1d7c01..d917770b64 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/__init__.py @@ -12,10 +12,10 @@ 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 @@ -36,6 +36,7 @@ class BundleInstance(InstanceResource): + class EndUserType(object): INDIVIDUAL = "individual" BUSINESS = "business" @@ -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: """ @@ -238,6 +324,7 @@ def __repr__(self) -> str: class BundleContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the BundleContext @@ -258,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 @@ -265,9 +366,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -277,9 +400,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the BundleInstance 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) -> BundleInstance: @@ -289,17 +436,43 @@ def fetch(self) -> BundleInstance: :returns: The fetched BundleInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return BundleInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BundleInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> BundleInstance: """ @@ -308,17 +481,59 @@ async def fetch_async(self) -> BundleInstance: :returns: The fetched BundleInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return BundleInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return BundleInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + 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, @@ -337,6 +552,54 @@ def update( :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( { "Status": status, @@ -345,14 +608,15 @@ def update( "Email": email, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return BundleInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -371,22 +635,39 @@ async def update_async( :returns: The updated BundleInstance """ - data = values.of( - { - "Status": status, - "StatusCallback": status_callback, - "FriendlyName": friendly_name, - "Email": email, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return BundleInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -447,12 +728,14 @@ def __repr__(self) -> str: class BundlePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BundleInstance: """ Build an instance of BundleInstance :param payload: Payload response from the API """ + return BundleInstance(self._version, payload) def __repr__(self) -> str: @@ -465,6 +748,7 @@ def __repr__(self) -> str: class BundleList(ListResource): + def __init__(self, version: Version): """ Initialize the BundleList @@ -476,7 +760,7 @@ def __init__(self, version: Version): self._uri = "/RegulatoryCompliance/Bundles" - def create( + def _create( self, friendly_name: str, email: str, @@ -485,20 +769,15 @@ def create( iso_country: Union[str, object] = values.unset, end_user_type: Union["BundleInstance.EndUserType", object] = values.unset, number_type: Union[str, object] = values.unset, - ) -> BundleInstance: + is_test: Union[bool, object] = values.unset, + ) -> 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`. + Internal helper for create operation - :returns: The created BundleInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -508,18 +787,20 @@ def create( "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"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return BundleInstance(self._version, payload) + headers["Accept"] = "application/json" - async def create_async( + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( self, friendly_name: str, email: str, @@ -528,9 +809,10 @@ async def create_async( 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 + 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. @@ -538,37 +820,185 @@ async def create_async( :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 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 """ - data = values.of( - { - "FriendlyName": friendly_name, - "Email": email, - "StatusCallback": status_callback, - "RegulationSid": regulation_sid, - "IsoCountry": iso_country, - "EndUserType": end_user_type, - "NumberType": number_type, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, ) - return BundleInstance(self._version, payload) - def stream( + def create_with_http_info( self, - status: Union["BundleInstance.Status", object] = values.unset, + 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" + + 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, @@ -585,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 `tollfree`. + :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`. @@ -607,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, @@ -625,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, @@ -645,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 `tollfree`. + :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`. @@ -667,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, @@ -682,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, @@ -704,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 `tollfree`. + :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`. @@ -723,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, @@ -744,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, @@ -763,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 `tollfree`. + :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`. @@ -782,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, @@ -801,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, @@ -823,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 `tollfree`. + :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`. @@ -842,11 +1558,13 @@ def page( data = values.of( { "Status": status, + "BundleSids": bundle_sids, "FriendlyName": friendly_name, "RegulationSid": regulation_sid, "IsoCountry": iso_country, "NumberType": number_type, - "HasValidUntilDate": has_valid_until_date, + "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), @@ -858,16 +1576,24 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 BundlePage(self._version, response) 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, @@ -883,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 `tollfree`. + :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`. @@ -902,11 +1630,13 @@ async def page_async( data = values.of( { "Status": status, + "BundleSids": bundle_sids, "FriendlyName": friendly_name, "RegulationSid": regulation_sid, "IsoCountry": iso_country, "NumberType": number_type, - "HasValidUntilDate": has_valid_until_date, + "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), @@ -918,11 +1648,163 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 5a0cf036b9..d5f9d253c8 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/bundle_copy.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +24,7 @@ class BundleCopyInstance(InstanceResource): + class Status(object): DRAFT = "draft" PENDING_REVIEW = "pending-review" @@ -80,12 +81,14 @@ def __repr__(self) -> str: class BundleCopyPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BundleCopyInstance: """ Build an instance of BundleCopyInstance :param payload: Payload response from the API """ + return BundleCopyInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) @@ -100,6 +103,7 @@ def __repr__(self) -> str: class BundleCopyList(ListResource): + def __init__(self, version: Version, bundle_sid: str): """ Initialize the BundleCopyList @@ -118,6 +122,29 @@ def __init__(self, version: Version, bundle_sid: str): **self._solution ) + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + 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 ) -> BundleCopyInstance: @@ -128,20 +155,50 @@ def create( :returns: The created BundleCopyInstance """ + payload, _, _ = self._create(friendly_name=friendly_name) + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] + ) + + def create_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return BundleCopyInstance( - 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( @@ -154,21 +211,28 @@ async def create_async( :returns: The created BundleCopyInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - } + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return BundleCopyInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + async def create_with_http_info_async( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the BundleCopyInstance and return response metadata - return BundleCopyInstance( + :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, @@ -220,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, @@ -239,6 +353,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -265,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( @@ -273,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, @@ -297,8 +463,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return BundleCopyPage(self._version, response, self._solution) + 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 BundleCopyPage(self._version, response, solution=self._solution) async def page_async( self, @@ -324,10 +496,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return BundleCopyPage(self._version, response, self._solution) + 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: """ @@ -339,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: """ @@ -351,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 53ad9d7694..34107f1ca8 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/evaluation.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class EvaluationInstance(InstanceResource): + class Status(object): COMPLIANT = "compliant" NONCOMPLIANT = "noncompliant" @@ -53,7 +54,7 @@ def __init__( self.regulation_sid: Optional[str] = payload.get("regulation_sid") self.bundle_sid: Optional[str] = payload.get("bundle_sid") self.status: Optional["EvaluationInstance.Status"] = payload.get("status") - self.results: Optional[List[object]] = payload.get("results") + self.results: Optional[List[Dict[str, object]]] = payload.get("results") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -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 @@ -110,6 +130,7 @@ def __repr__(self) -> str: class EvaluationContext(InstanceContext): + def __init__(self, version: Version, bundle_sid: str, sid: str): """ Initialize the EvaluationContext @@ -131,6 +152,22 @@ def __init__(self, version: Version, bundle_sid: str, sid: str): ) ) + 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) -> EvaluationInstance: """ Fetch the EvaluationInstance @@ -138,18 +175,45 @@ def fetch(self) -> EvaluationInstance: :returns: The fetched EvaluationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], ) - return EvaluationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EvaluationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EvaluationInstance: """ @@ -158,18 +222,29 @@ async def fetch_async(self) -> EvaluationInstance: :returns: The fetched EvaluationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EvaluationInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], ) - return EvaluationInstance( + 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: """ @@ -182,12 +257,14 @@ def __repr__(self) -> str: class EvaluationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EvaluationInstance: """ Build an instance of EvaluationInstance :param payload: Payload response from the API """ + return EvaluationInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) @@ -202,6 +279,7 @@ def __repr__(self) -> str: class EvaluationList(ListResource): + def __init__(self, version: Version, bundle_sid: str): """ Initialize the EvaluationList @@ -220,6 +298,22 @@ def __init__(self, version: Version, bundle_sid: str): **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) -> EvaluationInstance: """ Create the EvaluationInstance @@ -227,15 +321,39 @@ def create(self) -> EvaluationInstance: :returns: The created EvaluationInstance """ - - payload = self._version.create( - method="POST", - uri=self._uri, + payload, _, _ = self._create() + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - return EvaluationInstance( + def create_with_http_info(self) -> ApiResponse: + """ + Create the EvaluationInstance and return response metadata + + + :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" + + return await self._version.create_with_response_info_async( + method="POST", uri=self._uri, headers=headers + ) async def create_async(self) -> EvaluationInstance: """ @@ -244,15 +362,23 @@ async def create_async(self) -> EvaluationInstance: :returns: The created EvaluationInstance """ - - payload = await self._version.create_async( - method="POST", - uri=self._uri, + payload, _, _ = await self._create_async() + return EvaluationInstance( + self._version, payload, bundle_sid=self._solution["bundle_sid"] ) - return EvaluationInstance( + 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, @@ -304,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, @@ -323,6 +499,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -349,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( @@ -357,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, @@ -381,8 +609,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return EvaluationPage(self._version, response, self._solution) + 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 EvaluationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -408,10 +642,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return EvaluationPage(self._version, response, self._solution) + 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: """ @@ -423,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: """ @@ -435,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 f5f36206bf..336ee64979 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/item_assignment.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class ItemAssignmentInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Item Assignment resource. :ivar bundle_sid: The unique string that we created to identify the Bundle resource. @@ -56,6 +55,7 @@ def __init__( "bundle_sid": bundle_sid, "sid": sid or self.sid, } + self._context: Optional[ItemAssignmentContext] = None @property @@ -92,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 @@ -110,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 @@ -121,6 +157,7 @@ def __repr__(self) -> str: class ItemAssignmentContext(InstanceContext): + def __init__(self, version: Version, bundle_sid: str, sid: str): """ Initialize the ItemAssignmentContext @@ -142,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 @@ -149,9 +200,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -161,9 +234,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ItemAssignmentInstance 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) -> ItemAssignmentInstance: @@ -173,18 +270,45 @@ def fetch(self) -> ItemAssignmentInstance: :returns: The fetched ItemAssignmentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], ) - return ItemAssignmentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ItemAssignmentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ItemAssignmentInstance: """ @@ -193,18 +317,29 @@ async def fetch_async(self) -> ItemAssignmentInstance: :returns: The fetched ItemAssignmentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ItemAssignmentInstance( + self._version, + payload, + bundle_sid=self._solution["bundle_sid"], + sid=self._solution["sid"], ) - return ItemAssignmentInstance( + 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: """ @@ -217,12 +352,14 @@ def __repr__(self) -> str: class ItemAssignmentPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ItemAssignmentInstance: """ Build an instance of ItemAssignmentInstance :param payload: Payload response from the API """ + return ItemAssignmentInstance( self._version, payload, bundle_sid=self._solution["bundle_sid"] ) @@ -237,6 +374,7 @@ def __repr__(self) -> str: class ItemAssignmentList(ListResource): + def __init__(self, version: Version, bundle_sid: str): """ Initialize the ItemAssignmentList @@ -255,54 +393,106 @@ 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 - - :param object_sid: The SID of an object bag that holds information of the different items. + Internal helper for create operation - :returns: The created ItemAssignmentInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "ObjectSid": object_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "ObjectSid": object_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -353,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, @@ -372,6 +612,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -398,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( @@ -406,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, @@ -430,8 +722,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ItemAssignmentPage(self._version, response, self._solution) + 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 ItemAssignmentPage(self._version, response, solution=self._solution) async def page_async( self, @@ -457,10 +755,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ItemAssignmentPage(self._version, response, self._solution) + 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: """ @@ -472,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: """ @@ -484,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 e8ab99ad71..cb9c9a46dd 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/bundle/replace_items.py @@ -12,10 +12,10 @@ 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 @@ -23,6 +23,7 @@ class ReplaceItemsInstance(InstanceResource): + class Status(object): DRAFT = "draft" PENDING_REVIEW = "pending-review" @@ -79,6 +80,7 @@ def __repr__(self) -> str: class ReplaceItemsList(ListResource): + def __init__(self, version: Version, bundle_sid: str): """ Initialize the ReplaceItemsList @@ -97,54 +99,108 @@ 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 - - :param from_bundle_sid: The source bundle sid to copy the item assignments from. + Internal helper for create operation - :returns: The created ReplaceItemsInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FromBundleSid": from_bundle_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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( { "FromBundleSid": from_bundle_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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 f9bc9d270f..eaf2f958f2 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/end_user.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class EndUserInstance(InstanceResource): + class Type(object): INDIVIDUAL = "individual" BUSINESS = "business" @@ -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 @@ -160,6 +234,7 @@ def __repr__(self) -> str: class EndUserContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the EndUserContext @@ -175,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 @@ -182,9 +271,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -194,9 +305,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance 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) -> EndUserInstance: @@ -206,17 +341,43 @@ def fetch(self) -> EndUserInstance: :returns: The fetched EndUserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EndUserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EndUserInstance: """ @@ -225,17 +386,55 @@ async def fetch_async(self) -> EndUserInstance: :returns: The fetched EndUserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EndUserInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + 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, @@ -250,20 +449,55 @@ def update( :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( { "FriendlyName": friendly_name, "Attributes": serialize.object(attributes), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -278,20 +512,29 @@ async def update_async( :returns: The updated EndUserInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Attributes": serialize.object(attributes), - } + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes ) + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -304,12 +547,14 @@ def __repr__(self) -> str: class EndUserPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: """ Build an instance of EndUserInstance :param payload: Payload response from the API """ + return EndUserInstance(self._version, payload) def __repr__(self) -> str: @@ -322,6 +567,7 @@ def __repr__(self) -> str: class EndUserList(ListResource): + def __init__(self, version: Version): """ Initialize the EndUserList @@ -333,6 +579,36 @@ def __init__(self, version: Version): self._uri = "/RegulatoryCompliance/EndUsers" + def _create( + self, + friendly_name: str, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + 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, @@ -348,6 +624,45 @@ def create( :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( { "FriendlyName": friendly_name, @@ -355,14 +670,15 @@ def create( "Attributes": serialize.object(attributes), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return EndUserInstance(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, @@ -379,21 +695,31 @@ async def create_async( :returns: The created EndUserInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Attributes": serialize.object(attributes), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes ) + return EndUserInstance(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, + type: "EndUserInstance.Type", + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the EndUserInstance and return response metadata - return EndUserInstance(self._version, payload) + :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, @@ -445,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, @@ -464,6 +840,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -490,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( @@ -498,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, @@ -522,7 +950,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 EndUserPage(self._version, response) async def page_async( @@ -549,11 +983,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 0a762cea38..cf6534bbed 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/end_user_type.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class EndUserTypeInstance(InstanceResource): - """ :ivar sid: The unique string that identifies the End-User Type resource. :ivar friendly_name: A human-readable description that is assigned to describe the End-User Type resource. Examples can include first name, last name, email, business name, etc @@ -40,12 +39,13 @@ def __init__( self.sid: Optional[str] = payload.get("sid") self.friendly_name: Optional[str] = payload.get("friendly_name") self.machine_name: Optional[str] = payload.get("machine_name") - self.fields: Optional[List[object]] = payload.get("fields") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") self.url: Optional[str] = payload.get("url") self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserTypeContext] = None @property @@ -81,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 @@ -92,6 +110,7 @@ def __repr__(self) -> str: class EndUserTypeContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the EndUserTypeContext @@ -107,6 +126,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RegulatoryCompliance/EndUserTypes/{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) -> EndUserTypeInstance: """ Fetch the EndUserTypeInstance @@ -114,17 +149,43 @@ def fetch(self) -> EndUserTypeInstance: :returns: The fetched EndUserTypeInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EndUserTypeInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EndUserTypeInstance: """ @@ -133,17 +194,27 @@ async def fetch_async(self) -> EndUserTypeInstance: :returns: The fetched EndUserTypeInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EndUserTypeInstance( + 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: """ @@ -156,12 +227,14 @@ def __repr__(self) -> str: class EndUserTypePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: """ Build an instance of EndUserTypeInstance :param payload: Payload response from the API """ + return EndUserTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -174,6 +247,7 @@ def __repr__(self) -> str: class EndUserTypeList(ListResource): + def __init__(self, version: Version): """ Initialize the EndUserTypeList @@ -235,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, @@ -254,6 +378,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -280,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( @@ -288,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, @@ -312,7 +488,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 EndUserTypePage(self._version, response) async def page_async( @@ -339,11 +521,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 ab0bf1a332..88a84f8518 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/regulation.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/regulation.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import values +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 @@ -23,6 +23,7 @@ class RegulationInstance(InstanceResource): + class EndUserType(object): INDIVIDUAL = "individual" BUSINESS = "business" @@ -55,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RegulationContext] = None @property @@ -72,23 +74,61 @@ def _proxy(self) -> "RegulationContext": ) return self._context - def fetch(self) -> "RegulationInstance": + 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 """ - return self._proxy.fetch() + return self._proxy.fetch( + include_constraints=include_constraints, + ) - async def fetch_async(self) -> "RegulationInstance": + 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 """ - return await self._proxy.fetch_async() + return await self._proxy.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: """ @@ -101,6 +141,7 @@ def __repr__(self) -> str: class RegulationContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the RegulationContext @@ -116,43 +157,125 @@ def __init__(self, version: Version, sid: str): } self._uri = "/RegulatoryCompliance/Regulations/{sid}".format(**self._solution) - def fetch(self) -> RegulationInstance: + def _fetch(self, include_constraints: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } + ) + + 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_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._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch(include_constraints=include_constraints) + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RegulationInstance( + def fetch_with_http_info( + self, include_constraints: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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) + + async def _fetch_async( + self, include_constraints: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation - async def fetch_async(self) -> RegulationInstance: + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "IncludeConstraints": serialize.boolean_to_string(include_constraints), + } + ) + + 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_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._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async(include_constraints=include_constraints) + return RegulationInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RegulationInstance( + 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: """ @@ -165,12 +288,14 @@ def __repr__(self) -> str: class RegulationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RegulationInstance: """ Build an instance of RegulationInstance :param payload: Payload response from the API """ + return RegulationInstance(self._version, payload) def __repr__(self) -> str: @@ -183,6 +308,7 @@ def __repr__(self) -> str: class RegulationList(ListResource): + def __init__(self, version: Version): """ Initialize the RegulationList @@ -199,6 +325,7 @@ def stream( 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, ) -> Iterator[RegulationInstance]: @@ -211,6 +338,7 @@ def stream( :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 @@ -225,6 +353,7 @@ def stream( end_user_type=end_user_type, iso_country=iso_country, number_type=number_type, + include_constraints=include_constraints, page_size=limits["page_size"], ) @@ -235,6 +364,7 @@ async def stream_async( 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, ) -> AsyncIterator[RegulationInstance]: @@ -247,6 +377,7 @@ async def stream_async( :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 @@ -261,16 +392,94 @@ async def stream_async( end_user_type=end_user_type, iso_country=iso_country, number_type=number_type, + include_constraints=include_constraints, page_size=limits["page_size"], ) 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, 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, ) -> List[RegulationInstance]: @@ -282,6 +491,7 @@ def list( :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 @@ -291,11 +501,13 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end_user_type=end_user_type, iso_country=iso_country, number_type=number_type, + include_constraints=include_constraints, limit=limit, page_size=page_size, ) @@ -306,6 +518,7 @@ async def list_async( 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, ) -> List[RegulationInstance]: @@ -317,6 +530,7 @@ async def list_async( :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 @@ -326,22 +540,99 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_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, ) ] + 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, 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, @@ -353,6 +644,7 @@ def page( :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 @@ -364,13 +656,20 @@ def page( "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, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 RegulationPage(self._version, response) async def page_async( @@ -378,6 +677,7 @@ async def page_async( 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, @@ -389,6 +689,7 @@ async def page_async( :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 @@ -400,17 +701,116 @@ async def page_async( "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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 e619ecdc26..abbddb13c1 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class SupportingDocumentInstance(InstanceResource): + class Status(object): DRAFT = "draft" PENDING_REVIEW = "pending-review" @@ -39,6 +40,7 @@ class Status(object): :ivar mime_type: The image type uploaded in the Supporting Document container. :ivar status: :ivar failure_reason: The failure reason of the Supporting Document Resource. + :ivar errors: A list of errors that occurred during the registering RC Bundle :ivar type: The type of the Supporting Document. :ivar attributes: The set of parameters that are the attributes of the Supporting Documents resource which are listed in the Supporting Document Types. :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. @@ -59,6 +61,7 @@ def __init__( "status" ) self.failure_reason: Optional[str] = payload.get("failure_reason") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") self.type: Optional[str] = payload.get("type") self.attributes: Optional[Dict[str, object]] = payload.get("attributes") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( @@ -72,6 +75,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentContext] = 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 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 @@ -125,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, @@ -161,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 @@ -172,6 +248,7 @@ def __repr__(self) -> str: class SupportingDocumentContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SupportingDocumentContext @@ -189,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 @@ -196,9 +287,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -208,9 +321,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance 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) -> SupportingDocumentInstance: @@ -220,17 +357,43 @@ def fetch(self) -> SupportingDocumentInstance: :returns: The fetched SupportingDocumentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SupportingDocumentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SupportingDocumentInstance: """ @@ -239,17 +402,55 @@ async def fetch_async(self) -> SupportingDocumentInstance: :returns: The fetched SupportingDocumentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SupportingDocumentInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + 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, @@ -264,21 +465,58 @@ def update( :returns: The updated SupportingDocumentInstance """ + payload, _, _ = self._update(friendly_name=friendly_name, attributes=attributes) + return SupportingDocumentInstance( + 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 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 = 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( { "FriendlyName": friendly_name, "Attributes": serialize.object(attributes), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SupportingDocumentInstance( - self._version, payload, sid=self._solution["sid"] + 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( @@ -294,22 +532,33 @@ async def update_async( :returns: The updated SupportingDocumentInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Attributes": serialize.object(attributes), - } + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] ) - return SupportingDocumentInstance( + 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: """ @@ -322,12 +571,14 @@ def __repr__(self) -> str: class SupportingDocumentPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: """ Build an instance of SupportingDocumentInstance :param payload: Payload response from the API """ + return SupportingDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -340,6 +591,7 @@ def __repr__(self) -> str: class SupportingDocumentList(ListResource): + def __init__(self, version: Version): """ Initialize the SupportingDocumentList @@ -351,6 +603,36 @@ def __init__(self, version: Version): self._uri = "/RegulatoryCompliance/SupportingDocuments" + def _create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + 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, @@ -366,6 +648,45 @@ def create( :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( { "FriendlyName": friendly_name, @@ -373,14 +694,15 @@ def create( "Attributes": serialize.object(attributes), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SupportingDocumentInstance(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, @@ -397,21 +719,31 @@ async def create_async( :returns: The created SupportingDocumentInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Attributes": serialize.object(attributes), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes ) + return SupportingDocumentInstance(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, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SupportingDocumentInstance and return response metadata - return SupportingDocumentInstance(self._version, payload) + :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, @@ -463,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, @@ -482,6 +864,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -508,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( @@ -516,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, @@ -540,7 +974,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SupportingDocumentPage(self._version, response) async def page_async( @@ -567,11 +1007,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 65c097b994..d2de945f94 100644 --- a/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py +++ b/twilio/rest/numbers/v2/regulatory_compliance/supporting_document_type.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class SupportingDocumentTypeInstance(InstanceResource): - """ :ivar sid: The unique string that identifies the Supporting Document Type resource. :ivar friendly_name: A human-readable description of the Supporting Document Type resource. @@ -40,12 +39,13 @@ def __init__( self.sid: Optional[str] = payload.get("sid") self.friendly_name: Optional[str] = payload.get("friendly_name") self.machine_name: Optional[str] = payload.get("machine_name") - self.fields: Optional[List[object]] = payload.get("fields") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") self.url: Optional[str] = payload.get("url") self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentTypeContext] = None @property @@ -81,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 @@ -92,6 +110,7 @@ def __repr__(self) -> str: class SupportingDocumentTypeContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SupportingDocumentTypeContext @@ -109,6 +128,22 @@ def __init__(self, version: Version, sid: str): **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) -> SupportingDocumentTypeInstance: """ Fetch the SupportingDocumentTypeInstance @@ -116,17 +151,43 @@ def fetch(self) -> SupportingDocumentTypeInstance: :returns: The fetched SupportingDocumentTypeInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SupportingDocumentTypeInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SupportingDocumentTypeInstance: """ @@ -135,17 +196,27 @@ async def fetch_async(self) -> SupportingDocumentTypeInstance: :returns: The fetched SupportingDocumentTypeInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SupportingDocumentTypeInstance( + 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: """ @@ -158,12 +229,14 @@ def __repr__(self) -> str: class SupportingDocumentTypePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstance: """ Build an instance of SupportingDocumentTypeInstance :param payload: Payload response from the API """ + return SupportingDocumentTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -176,6 +249,7 @@ def __repr__(self) -> str: class SupportingDocumentTypeList(ListResource): + def __init__(self, version: Version): """ Initialize the SupportingDocumentTypeList @@ -237,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, @@ -256,6 +380,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -282,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( @@ -290,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, @@ -314,7 +490,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SupportingDocumentTypePage(self._version, response) async def page_async( @@ -341,11 +523,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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/preview/understand/__init__.py b/twilio/rest/numbers/v3/__init__.py similarity index 58% rename from twilio/rest/preview/understand/__init__.py rename to twilio/rest/numbers/v3/__init__.py index da659fd3a6..9826e176fb 100644 --- a/twilio/rest/preview/understand/__init__.py +++ b/twilio/rest/numbers/v3/__init__.py @@ -4,7 +4,7 @@ | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - Twilio - Preview + Twilio - Numbers This is the public Twilio REST API. NOTE: This class is auto generated by OpenAPI Generator. @@ -15,28 +15,29 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain -from twilio.rest.preview.understand.assistant import AssistantList +from twilio.rest.numbers.v3.hosted_number_order import HostedNumberOrderList -class Understand(Version): +class V3(Version): + def __init__(self, domain: Domain): """ - Initialize the Understand version of Preview + Initialize the V3 version of Numbers - :param domain: The Twilio.preview domain + :param domain: The Twilio.numbers domain """ - super().__init__(domain, "understand") - self._assistants: Optional[AssistantList] = None + super().__init__(domain, "v3") + self._hosted_number_orders: Optional[HostedNumberOrderList] = None @property - def assistants(self) -> AssistantList: - if self._assistants is None: - self._assistants = AssistantList(self) - return self._assistants + 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 "" + return "" 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 "" + + +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 "" diff --git a/twilio/rest/oauth/OauthBase.py b/twilio/rest/oauth/OauthBase.py index 3df051d0fc..b26f459963 100644 --- a/twilio/rest/oauth/OauthBase.py +++ b/twilio/rest/oauth/OauthBase.py @@ -14,9 +14,11 @@ 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): + def __init__(self, twilio: Client): """ Initialize the Oauth Domain @@ -25,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: @@ -35,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/__init__.py b/twilio/rest/oauth/__init__.py index 709150e9e0..586cf6b4d9 100644 --- a/twilio/rest/oauth/__init__.py +++ b/twilio/rest/oauth/__init__.py @@ -1,40 +1,10 @@ from warnings import warn from twilio.rest.oauth.OauthBase import OauthBase -from twilio.rest.oauth.v1.device_code import DeviceCodeList -from twilio.rest.oauth.v1.oauth import OauthList -from twilio.rest.oauth.v1.openid_discovery import OpenidDiscoveryList from twilio.rest.oauth.v1.token import TokenList -from twilio.rest.oauth.v1.user_info import UserInfoList class Oauth(OauthBase): - @property - def oauth(self) -> OauthList: - warn( - "oauth is deprecated. Use v1.oauth instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.oauth - - @property - def device_code(self) -> DeviceCodeList: - warn( - "device_code is deprecated. Use v1.device_code instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.device_code - - @property - def openid_discovery(self) -> OpenidDiscoveryList: - warn( - "openid_discovery is deprecated. Use v1.openid_discovery instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.openid_discovery @property def token(self) -> TokenList: @@ -44,12 +14,3 @@ def token(self) -> TokenList: stacklevel=2, ) return self.v1.token - - @property - def user_info(self) -> UserInfoList: - warn( - "user_info is deprecated. Use v1.user_info instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.v1.user_info diff --git a/twilio/rest/oauth/v1/__init__.py b/twilio/rest/oauth/v1/__init__.py index 36aaa90ff3..e05c7de520 100644 --- a/twilio/rest/oauth/v1/__init__.py +++ b/twilio/rest/oauth/v1/__init__.py @@ -15,14 +15,12 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain -from twilio.rest.oauth.v1.device_code import DeviceCodeList -from twilio.rest.oauth.v1.oauth import OauthList -from twilio.rest.oauth.v1.openid_discovery import OpenidDiscoveryList +from twilio.rest.oauth.v1.authorize import AuthorizeList from twilio.rest.oauth.v1.token import TokenList -from twilio.rest.oauth.v1.user_info import UserInfoList class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Oauth @@ -30,29 +28,14 @@ def __init__(self, domain: Domain): :param domain: The Twilio.oauth domain """ super().__init__(domain, "v1") - self._device_code: Optional[DeviceCodeList] = None - self._oauth: Optional[OauthList] = None - self._openid_discovery: Optional[OpenidDiscoveryList] = None + self._authorize: Optional[AuthorizeList] = None self._token: Optional[TokenList] = None - self._user_info: Optional[UserInfoList] = None - - @property - def device_code(self) -> DeviceCodeList: - if self._device_code is None: - self._device_code = DeviceCodeList(self) - return self._device_code @property - def oauth(self) -> OauthList: - if self._oauth is None: - self._oauth = OauthList(self) - return self._oauth - - @property - def openid_discovery(self) -> OpenidDiscoveryList: - if self._openid_discovery is None: - self._openid_discovery = OpenidDiscoveryList(self) - return self._openid_discovery + def authorize(self) -> AuthorizeList: + if self._authorize is None: + self._authorize = AuthorizeList(self) + return self._authorize @property def token(self) -> TokenList: @@ -60,12 +43,6 @@ def token(self) -> TokenList: self._token = TokenList(self) return self._token - @property - def user_info(self) -> UserInfoList: - if self._user_info is None: - self._user_info = UserInfoList(self) - return self._user_info - def __repr__(self) -> str: """ Provide a friendly representation diff --git a/twilio/rest/oauth/v1/authorize.py b/twilio/rest/oauth/v1/authorize.py new file mode 100644 index 0000000000..69ff398da9 --- /dev/null +++ b/twilio/rest/oauth/v1/authorize.py @@ -0,0 +1,221 @@ +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, 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 "" + + +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, + ) -> 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( + { + "ResponseType": response_type, + "ClientId": client_id, + "RedirectUri": redirect_uri, + "Scope": scope, + "State": state, + } + ) + + 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, + ) -> 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" + + params = values.of( + { + "ResponseType": response_type, + "ClientId": client_id, + "RedirectUri": redirect_uri, + "Scope": scope, + "State": state, + } + ) + + 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/oauth/v1/device_code.py b/twilio/rest/oauth/v1/device_code.py deleted file mode 100644 index ed0998ee94..0000000000 --- a/twilio/rest/oauth/v1/device_code.py +++ /dev/null @@ -1,137 +0,0 @@ -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, List, 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 DeviceCodeInstance(InstanceResource): - - """ - :ivar device_code: The device verification code. - :ivar user_code: The verification code which end user uses to verify authorization request. - :ivar verification_uri: The URI that the end user visits to verify authorization request. - :ivar verification_uri_complete: The URI with user_code that the end-user alternatively visits to verify authorization request. - :ivar expires_in: The expiration time of the device_code and user_code in seconds. - :ivar interval: The minimum amount of time in seconds that the client should wait between polling requests to the token endpoint. - """ - - def __init__(self, version: Version, payload: Dict[str, Any]): - super().__init__(version) - - self.device_code: Optional[str] = payload.get("device_code") - self.user_code: Optional[str] = payload.get("user_code") - self.verification_uri: Optional[str] = payload.get("verification_uri") - self.verification_uri_complete: Optional[str] = payload.get( - "verification_uri_complete" - ) - self.expires_in: Optional[int] = payload.get("expires_in") - self.interval: Optional[int] = deserialize.integer(payload.get("interval")) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class DeviceCodeList(ListResource): - def __init__(self, version: Version): - """ - Initialize the DeviceCodeList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/device/code" - - def create( - self, - client_sid: str, - scopes: List[str], - audiences: Union[List[str], object] = values.unset, - ) -> DeviceCodeInstance: - """ - Create the DeviceCodeInstance - - :param client_sid: A 34 character string that uniquely identifies this OAuth App. - :param scopes: An Array of scopes for authorization request - :param audiences: An array of intended audiences for token requests - - :returns: The created DeviceCodeInstance - """ - data = values.of( - { - "ClientSid": client_sid, - "Scopes": serialize.map(scopes, lambda e: e), - "Audiences": serialize.map(audiences, lambda e: e), - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return DeviceCodeInstance(self._version, payload) - - async def create_async( - self, - client_sid: str, - scopes: List[str], - audiences: Union[List[str], object] = values.unset, - ) -> DeviceCodeInstance: - """ - Asynchronously create the DeviceCodeInstance - - :param client_sid: A 34 character string that uniquely identifies this OAuth App. - :param scopes: An Array of scopes for authorization request - :param audiences: An array of intended audiences for token requests - - :returns: The created DeviceCodeInstance - """ - data = values.of( - { - "ClientSid": client_sid, - "Scopes": serialize.map(scopes, lambda e: e), - "Audiences": serialize.map(audiences, lambda e: e), - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return DeviceCodeInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/oauth/v1/oauth.py b/twilio/rest/oauth/v1/oauth.py deleted file mode 100644 index 3765b65180..0000000000 --- a/twilio/rest/oauth/v1/oauth.py +++ /dev/null @@ -1,167 +0,0 @@ -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.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 OauthInstance(InstanceResource): - - """ - :ivar keys: A collection of certificates where are signed Twilio-issued tokens. - :ivar url: - """ - - def __init__(self, version: Version, payload: Dict[str, Any]): - super().__init__(version) - - self.keys: Optional[Dict[str, object]] = payload.get("keys") - self.url: Optional[str] = payload.get("url") - - self._context: Optional[OauthContext] = None - - @property - def _proxy(self) -> "OauthContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: OauthContext for this OauthInstance - """ - if self._context is None: - self._context = OauthContext( - self._version, - ) - return self._context - - def fetch(self) -> "OauthInstance": - """ - Fetch the OauthInstance - - - :returns: The fetched OauthInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "OauthInstance": - """ - Asynchronous coroutine to fetch the OauthInstance - - - :returns: The fetched OauthInstance - """ - return await self._proxy.fetch_async() - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class OauthContext(InstanceContext): - def __init__(self, version: Version): - """ - Initialize the OauthContext - - :param version: Version that contains the resource - """ - super().__init__(version) - - self._uri = "/certs" - - def fetch(self) -> OauthInstance: - """ - Fetch the OauthInstance - - - :returns: The fetched OauthInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return OauthInstance( - self._version, - payload, - ) - - async def fetch_async(self) -> OauthInstance: - """ - Asynchronous coroutine to fetch the OauthInstance - - - :returns: The fetched OauthInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return OauthInstance( - self._version, - payload, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class OauthList(ListResource): - def __init__(self, version: Version): - """ - Initialize the OauthList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - def get(self) -> OauthContext: - """ - Constructs a OauthContext - - """ - return OauthContext(self._version) - - def __call__(self) -> OauthContext: - """ - Constructs a OauthContext - - """ - return OauthContext(self._version) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/oauth/v1/openid_discovery.py b/twilio/rest/oauth/v1/openid_discovery.py deleted file mode 100644 index 00a551a2fe..0000000000 --- a/twilio/rest/oauth/v1/openid_discovery.py +++ /dev/null @@ -1,199 +0,0 @@ -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, List, Optional -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 OpenidDiscoveryInstance(InstanceResource): - - """ - :ivar issuer: The URL of the party that will create the token and sign it with its private key. - :ivar authorization_endpoint: The endpoint that validates all authorization requests. - :ivar device_authorization_endpoint: The endpoint that validates all device code related authorization requests. - :ivar token_endpoint: The URL of the token endpoint. After a client has received an authorization code, that code is presented to the token endpoint and exchanged for an identity token, an access token, and a refresh token. - :ivar userinfo_endpoint: The URL of the user info endpoint, which returns user profile information to a client. Keep in mind that the user info endpoint returns only the information that has been requested. - :ivar revocation_endpoint: The endpoint used to revoke access or refresh tokens issued by the authorization server. - :ivar jwk_uri: The URL of your JSON Web Key Set. This set is a collection of JSON Web Keys, a standard method for representing cryptographic keys in a JSON structure. - :ivar response_type_supported: A collection of response type supported by authorization server. - :ivar subject_type_supported: A collection of subject by authorization server. - :ivar id_token_signing_alg_values_supported: A collection of JWS signing algorithms supported by authorization server to sign identity token. - :ivar scopes_supported: A collection of scopes supported by authorization server for identity token - :ivar claims_supported: A collection of claims supported by authorization server for identity token - :ivar url: - """ - - 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.device_authorization_endpoint: Optional[str] = payload.get( - "device_authorization_endpoint" - ) - self.token_endpoint: Optional[str] = payload.get("token_endpoint") - self.userinfo_endpoint: Optional[str] = payload.get("userinfo_endpoint") - self.revocation_endpoint: Optional[str] = payload.get("revocation_endpoint") - self.jwk_uri: Optional[str] = payload.get("jwk_uri") - self.response_type_supported: Optional[List[str]] = payload.get( - "response_type_supported" - ) - self.subject_type_supported: Optional[List[str]] = payload.get( - "subject_type_supported" - ) - self.id_token_signing_alg_values_supported: Optional[List[str]] = payload.get( - "id_token_signing_alg_values_supported" - ) - self.scopes_supported: Optional[List[str]] = payload.get("scopes_supported") - self.claims_supported: Optional[List[str]] = payload.get("claims_supported") - self.url: Optional[str] = payload.get("url") - - self._context: Optional[OpenidDiscoveryContext] = None - - @property - def _proxy(self) -> "OpenidDiscoveryContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: OpenidDiscoveryContext for this OpenidDiscoveryInstance - """ - if self._context is None: - self._context = OpenidDiscoveryContext( - self._version, - ) - return self._context - - def fetch(self) -> "OpenidDiscoveryInstance": - """ - Fetch the OpenidDiscoveryInstance - - - :returns: The fetched OpenidDiscoveryInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "OpenidDiscoveryInstance": - """ - Asynchronous coroutine to fetch the OpenidDiscoveryInstance - - - :returns: The fetched OpenidDiscoveryInstance - """ - return await self._proxy.fetch_async() - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class OpenidDiscoveryContext(InstanceContext): - def __init__(self, version: Version): - """ - Initialize the OpenidDiscoveryContext - - :param version: Version that contains the resource - """ - super().__init__(version) - - self._uri = "/.well-known/openid-configuration" - - def fetch(self) -> OpenidDiscoveryInstance: - """ - Fetch the OpenidDiscoveryInstance - - - :returns: The fetched OpenidDiscoveryInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return OpenidDiscoveryInstance( - self._version, - payload, - ) - - async def fetch_async(self) -> OpenidDiscoveryInstance: - """ - Asynchronous coroutine to fetch the OpenidDiscoveryInstance - - - :returns: The fetched OpenidDiscoveryInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return OpenidDiscoveryInstance( - self._version, - payload, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class OpenidDiscoveryList(ListResource): - def __init__(self, version: Version): - """ - Initialize the OpenidDiscoveryList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - def get(self) -> OpenidDiscoveryContext: - """ - Constructs a OpenidDiscoveryContext - - """ - return OpenidDiscoveryContext(self._version) - - def __call__(self) -> OpenidDiscoveryContext: - """ - Constructs a OpenidDiscoveryContext - - """ - return OpenidDiscoveryContext(self._version) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/oauth/v1/token.py b/twilio/rest/oauth/v1/token.py index d236731a9f..ebf53dc523 100644 --- a/twilio/rest/oauth/v1/token.py +++ b/twilio/rest/oauth/v1/token.py @@ -12,10 +12,9 @@ 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 import values +from twilio.base.api_response import ApiResponse from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,13 +22,12 @@ 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: - :ivar refresh_token_expires_at: The date and time in GMT when the refresh token expires in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. - :ivar access_token_expires_at: The date and time in GMT when the refresh token expires in [RFC 2822](https://www.ietf.org/rfc/rfc2822.txt) format. + :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]): @@ -38,12 +36,8 @@ def __init__(self, version: Version, payload: Dict[str, Any]): 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.refresh_token_expires_at: Optional[ - datetime - ] = deserialize.iso8601_datetime(payload.get("refresh_token_expires_at")) - self.access_token_expires_at: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("access_token_expires_at") - ) + self.token_type: Optional[str] = payload.get("token_type") + self.expires_in: Optional[int] = payload.get("expires_in") def __repr__(self) -> str: """ @@ -56,6 +50,7 @@ def __repr__(self) -> str: class TokenList(ListResource): + def __init__(self, version: Version): """ Initialize the TokenList @@ -67,97 +62,235 @@ def __init__(self, version: 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( + { + "GrantType": grant_type, + "ClientId": client_id, + "ClientSecret": client_secret, + "Code": code, + "RedirectUri": redirect_uri, + "Audience": audience, + "RefreshToken": 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_sid: str, + client_id: str, client_secret: Union[str, object] = values.unset, code: Union[str, object] = values.unset, - code_verifier: Union[str, object] = values.unset, - device_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, - device_id: 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_sid: A 34 character string that uniquely identifies this OAuth App. + :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 code_verifier: A code which is generation cryptographically. - :param device_code: JWT token related to the device code grant type. - :param refresh_token: JWT token related to the refresh token grant type. - :param device_id: The Id of the device associated with the token (refresh token). + :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( { "GrantType": grant_type, - "ClientSid": client_sid, + "ClientId": client_id, "ClientSecret": client_secret, "Code": code, - "CodeVerifier": code_verifier, - "DeviceCode": device_code, + "RedirectUri": redirect_uri, + "Audience": audience, "RefreshToken": refresh_token, - "DeviceId": device_id, + "Scope": scope, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return TokenInstance(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, grant_type: str, - client_sid: str, + client_id: str, client_secret: Union[str, object] = values.unset, code: Union[str, object] = values.unset, - code_verifier: Union[str, object] = values.unset, - device_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, - device_id: 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_sid: A 34 character string that uniquely identifies this OAuth App. + :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 code_verifier: A code which is generation cryptographically. - :param device_code: JWT token related to the device code grant type. - :param refresh_token: JWT token related to the refresh token grant type. - :param device_id: The Id of the device associated with the token (refresh token). + :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 """ - data = values.of( - { - "GrantType": grant_type, - "ClientSid": client_sid, - "ClientSecret": client_secret, - "Code": code, - "CodeVerifier": code_verifier, - "DeviceCode": device_code, - "RefreshToken": refresh_token, - "DeviceId": device_id, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return TokenInstance(self._version, payload) + :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: """ diff --git a/twilio/rest/oauth/v1/user_info.py b/twilio/rest/oauth/v1/user_info.py deleted file mode 100644 index f7b7f0f5df..0000000000 --- a/twilio/rest/oauth/v1/user_info.py +++ /dev/null @@ -1,175 +0,0 @@ -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.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 UserInfoInstance(InstanceResource): - - """ - :ivar user_sid: The URL of the party that will create the token and sign it with its private key. - :ivar first_name: The first name of the end-user. - :ivar last_name: The last name of the end-user. - :ivar friendly_name: The friendly name of the end-user. - :ivar email: The end-user's preferred email address. - :ivar url: - """ - - def __init__(self, version: Version, payload: Dict[str, Any]): - super().__init__(version) - - self.user_sid: Optional[str] = payload.get("user_sid") - self.first_name: Optional[str] = payload.get("first_name") - self.last_name: Optional[str] = payload.get("last_name") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.email: Optional[str] = payload.get("email") - self.url: Optional[str] = payload.get("url") - - self._context: Optional[UserInfoContext] = None - - @property - def _proxy(self) -> "UserInfoContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: UserInfoContext for this UserInfoInstance - """ - if self._context is None: - self._context = UserInfoContext( - self._version, - ) - return self._context - - def fetch(self) -> "UserInfoInstance": - """ - Fetch the UserInfoInstance - - - :returns: The fetched UserInfoInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "UserInfoInstance": - """ - Asynchronous coroutine to fetch the UserInfoInstance - - - :returns: The fetched UserInfoInstance - """ - return await self._proxy.fetch_async() - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class UserInfoContext(InstanceContext): - def __init__(self, version: Version): - """ - Initialize the UserInfoContext - - :param version: Version that contains the resource - """ - super().__init__(version) - - self._uri = "/userinfo" - - def fetch(self) -> UserInfoInstance: - """ - Fetch the UserInfoInstance - - - :returns: The fetched UserInfoInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return UserInfoInstance( - self._version, - payload, - ) - - async def fetch_async(self) -> UserInfoInstance: - """ - Asynchronous coroutine to fetch the UserInfoInstance - - - :returns: The fetched UserInfoInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return UserInfoInstance( - self._version, - payload, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - - return "" - - -class UserInfoList(ListResource): - def __init__(self, version: Version): - """ - Initialize the UserInfoList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - def get(self) -> UserInfoContext: - """ - Constructs a UserInfoContext - - """ - return UserInfoContext(self._version) - - def __call__(self) -> UserInfoContext: - """ - Constructs a UserInfoContext - - """ - return UserInfoContext(self._version) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" 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 "" diff --git a/twilio/rest/oauth/v2/authorize.py b/twilio/rest/oauth/v2/authorize.py new file mode 100644 index 0000000000..53841e7188 --- /dev/null +++ b/twilio/rest/oauth/v2/authorize.py @@ -0,0 +1,221 @@ +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 "" + + +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, + ) -> 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, + } + ) + + 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, + ) -> AuthorizeInstance: + """ + Fetch the AuthorizeInstance + + :param response_type: :param client_id: :param redirect_uri: :param scope: :param state: + :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: :param client_id: :param redirect_uri: :param scope: :param state: + :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" + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + } + ) + + 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: :param client_id: :param redirect_uri: :param scope: :param state: + :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: :param client_id: :param redirect_uri: :param scope: :param state: + :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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/oauth/v2/token.py b/twilio/rest/oauth/v2/token.py new file mode 100644 index 0000000000..3550e4b506 --- /dev/null +++ b/twilio/rest/oauth/v2/token.py @@ -0,0 +1,327 @@ +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 "" + + +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, + ) -> 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" + + 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, + ) -> 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 + + :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, + ) + 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, + ) -> 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 + + :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, + ) + 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, + ) -> 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" + + 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, + ) -> 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 + + :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, + ) + 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, + ) -> 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 + + :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, + ) + 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/preview/PreviewBase.py b/twilio/rest/preview/PreviewBase.py index 73d5aac4bd..dd8317b4c0 100644 --- a/twilio/rest/preview/PreviewBase.py +++ b/twilio/rest/preview/PreviewBase.py @@ -13,15 +13,13 @@ from twilio.base.domain import Domain from twilio.rest import Client -from twilio.rest.preview.deployed_devices import DeployedDevices 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.understand import Understand from twilio.rest.preview.wireless import Wireless class PreviewBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Preview Domain @@ -29,22 +27,10 @@ def __init__(self, twilio: Client): :returns: Domain for Preview """ super().__init__(twilio, "https://preview.twilio.com") - self._deployed_devices: Optional[DeployedDevices] = None self._hosted_numbers: Optional[HostedNumbers] = None - self._sync: Optional[Sync] = None self._marketplace: Optional[Marketplace] = None - self._understand: Optional[Understand] = None self._wireless: Optional[Wireless] = None - @property - def deployed_devices(self) -> DeployedDevices: - """ - :returns: Versions deployed_devices of Preview - """ - if self._deployed_devices is None: - self._deployed_devices = DeployedDevices(self) - return self._deployed_devices - @property def hosted_numbers(self) -> HostedNumbers: """ @@ -54,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: """ @@ -72,15 +49,6 @@ def marketplace(self) -> Marketplace: self._marketplace = Marketplace(self) return self._marketplace - @property - def understand(self) -> Understand: - """ - :returns: Versions understand of Preview - """ - if self._understand is None: - self._understand = Understand(self) - return self._understand - @property def wireless(self) -> Wireless: """ diff --git a/twilio/rest/preview/__init__.py b/twilio/rest/preview/__init__.py index 6933f3627c..c4658c62e3 100644 --- a/twilio/rest/preview/__init__.py +++ b/twilio/rest/preview/__init__.py @@ -1,29 +1,18 @@ from warnings import warn from twilio.rest.preview.PreviewBase import PreviewBase -from twilio.rest.preview.deployed_devices.fleet import FleetList from twilio.rest.preview.hosted_numbers.authorization_document import ( AuthorizationDocumentList, ) 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.understand.assistant import AssistantList 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 class Preview(PreviewBase): - @property - def fleets(self) -> FleetList: - warn( - "fleets is deprecated. Use deployed_devices.fleets instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.deployed_devices.fleets @property def authorization_documents(self) -> AuthorizationDocumentList: @@ -61,24 +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 assistants(self) -> AssistantList: - warn( - "assistants is deprecated. Use understand.assistants instead.", - DeprecationWarning, - stacklevel=2, - ) - return self.understand.assistants - @property def commands(self) -> CommandList: warn( diff --git a/twilio/rest/preview/deployed_devices/fleet/__init__.py b/twilio/rest/preview/deployed_devices/fleet/__init__.py deleted file mode 100644 index cb0c45498a..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/__init__.py +++ /dev/null @@ -1,673 +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.deployed_devices.fleet.certificate import CertificateList -from twilio.rest.preview.deployed_devices.fleet.deployment import DeploymentList -from twilio.rest.preview.deployed_devices.fleet.device import DeviceList -from twilio.rest.preview.deployed_devices.fleet.key import KeyList - - -class FleetInstance(InstanceResource): - - """ - :ivar sid: Contains a 34 character string that uniquely identifies this Fleet resource. - :ivar url: Contains an absolute URL for this Fleet resource. - :ivar unique_name: Contains a unique and addressable name of this Fleet, e.g. 'default', up to 128 characters long. - :ivar friendly_name: Contains a human readable descriptive text for this Fleet, up to 256 characters long. - :ivar account_sid: Speicifies the unique string identifier of the Account responsible for this Fleet. - :ivar default_deployment_sid: Contains the string identifier of the automatically provisioned default Deployment of this Fleet. - :ivar date_created: Specifies the date this Fleet was created, given in UTC ISO 8601 format. - :ivar date_updated: Specifies the date this Fleet was last updated, given in UTC ISO 8601 format. - :ivar links: Contains a dictionary of URL links to nested resources of this Fleet. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.url: Optional[str] = payload.get("url") - self.unique_name: Optional[str] = payload.get("unique_name") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.account_sid: Optional[str] = payload.get("account_sid") - self.default_deployment_sid: Optional[str] = payload.get( - "default_deployment_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.links: Optional[Dict[str, object]] = payload.get("links") - - self._solution = { - "sid": sid or self.sid, - } - self._context: Optional[FleetContext] = None - - @property - def _proxy(self) -> "FleetContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FleetContext for this FleetInstance - """ - if self._context is None: - self._context = FleetContext( - self._version, - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the FleetInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FleetInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "FleetInstance": - """ - Fetch the FleetInstance - - - :returns: The fetched FleetInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "FleetInstance": - """ - Asynchronous coroutine to fetch the FleetInstance - - - :returns: The fetched FleetInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - friendly_name: Union[str, object] = values.unset, - default_deployment_sid: Union[str, object] = values.unset, - ) -> "FleetInstance": - """ - Update the FleetInstance - - :param friendly_name: Provides a human readable descriptive text for this Fleet, up to 256 characters long. - :param default_deployment_sid: Provides a string identifier of a Deployment that is going to be used as a default one for this Fleet. - - :returns: The updated FleetInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - default_deployment_sid=default_deployment_sid, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - default_deployment_sid: Union[str, object] = values.unset, - ) -> "FleetInstance": - """ - Asynchronous coroutine to update the FleetInstance - - :param friendly_name: Provides a human readable descriptive text for this Fleet, up to 256 characters long. - :param default_deployment_sid: Provides a string identifier of a Deployment that is going to be used as a default one for this Fleet. - - :returns: The updated FleetInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - default_deployment_sid=default_deployment_sid, - ) - - @property - def certificates(self) -> CertificateList: - """ - Access the certificates - """ - return self._proxy.certificates - - @property - def deployments(self) -> DeploymentList: - """ - Access the deployments - """ - return self._proxy.deployments - - @property - def devices(self) -> DeviceList: - """ - Access the devices - """ - return self._proxy.devices - - @property - def keys(self) -> KeyList: - """ - Access the keys - """ - return self._proxy.keys - - 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 FleetContext(InstanceContext): - def __init__(self, version: Version, sid: str): - """ - Initialize the FleetContext - - :param version: Version that contains the resource - :param sid: Provides a 34 character string that uniquely identifies the requested Fleet resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Fleets/{sid}".format(**self._solution) - - self._certificates: Optional[CertificateList] = None - self._deployments: Optional[DeploymentList] = None - self._devices: Optional[DeviceList] = None - self._keys: Optional[KeyList] = None - - def delete(self) -> bool: - """ - Deletes the FleetInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FleetInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> FleetInstance: - """ - Fetch the FleetInstance - - - :returns: The fetched FleetInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return FleetInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> FleetInstance: - """ - Asynchronous coroutine to fetch the FleetInstance - - - :returns: The fetched FleetInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return FleetInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - default_deployment_sid: Union[str, object] = values.unset, - ) -> FleetInstance: - """ - Update the FleetInstance - - :param friendly_name: Provides a human readable descriptive text for this Fleet, up to 256 characters long. - :param default_deployment_sid: Provides a string identifier of a Deployment that is going to be used as a default one for this Fleet. - - :returns: The updated FleetInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultDeploymentSid": default_deployment_sid, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return FleetInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - default_deployment_sid: Union[str, object] = values.unset, - ) -> FleetInstance: - """ - Asynchronous coroutine to update the FleetInstance - - :param friendly_name: Provides a human readable descriptive text for this Fleet, up to 256 characters long. - :param default_deployment_sid: Provides a string identifier of a Deployment that is going to be used as a default one for this Fleet. - - :returns: The updated FleetInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "DefaultDeploymentSid": default_deployment_sid, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FleetInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def certificates(self) -> CertificateList: - """ - Access the certificates - """ - if self._certificates is None: - self._certificates = CertificateList( - self._version, - self._solution["sid"], - ) - return self._certificates - - @property - def deployments(self) -> DeploymentList: - """ - Access the deployments - """ - if self._deployments is None: - self._deployments = DeploymentList( - self._version, - self._solution["sid"], - ) - return self._deployments - - @property - def devices(self) -> DeviceList: - """ - Access the devices - """ - if self._devices is None: - self._devices = DeviceList( - self._version, - self._solution["sid"], - ) - return self._devices - - @property - def keys(self) -> KeyList: - """ - Access the keys - """ - if self._keys is None: - self._keys = KeyList( - self._version, - self._solution["sid"], - ) - return self._keys - - 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 FleetPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> FleetInstance: - """ - Build an instance of FleetInstance - - :param payload: Payload response from the API - """ - return FleetInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class FleetList(ListResource): - def __init__(self, version: Version): - """ - Initialize the FleetList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Fleets" - - def create(self, friendly_name: Union[str, object] = values.unset) -> FleetInstance: - """ - Create the FleetInstance - - :param friendly_name: Provides a human readable descriptive text for this Fleet, up to 256 characters long. - - :returns: The created FleetInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return FleetInstance(self._version, payload) - - async def create_async( - self, friendly_name: Union[str, object] = values.unset - ) -> FleetInstance: - """ - Asynchronously create the FleetInstance - - :param friendly_name: Provides a human readable descriptive text for this Fleet, up to 256 characters long. - - :returns: The created FleetInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FleetInstance(self._version, payload) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[FleetInstance]: - """ - Streams FleetInstance 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[FleetInstance]: - """ - Asynchronously streams FleetInstance 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[FleetInstance]: - """ - Lists FleetInstance 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[FleetInstance]: - """ - Asynchronously lists FleetInstance 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, - ) -> FleetPage: - """ - Retrieve a single page of FleetInstance 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 FleetInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return FleetPage(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, - ) -> FleetPage: - """ - Asynchronously retrieve a single page of FleetInstance 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 FleetInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return FleetPage(self._version, response) - - def get_page(self, target_url: str) -> FleetPage: - """ - Retrieve a specific page of FleetInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FleetInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return FleetPage(self._version, response) - - async def get_page_async(self, target_url: str) -> FleetPage: - """ - Asynchronously retrieve a specific page of FleetInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FleetInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return FleetPage(self._version, response) - - def get(self, sid: str) -> FleetContext: - """ - Constructs a FleetContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Fleet resource. - """ - return FleetContext(self._version, sid=sid) - - def __call__(self, sid: str) -> FleetContext: - """ - Constructs a FleetContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Fleet resource. - """ - return FleetContext(self._version, sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/deployed_devices/fleet/certificate.py b/twilio/rest/preview/deployed_devices/fleet/certificate.py deleted file mode 100644 index a6654de67e..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/certificate.py +++ /dev/null @@ -1,655 +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 - - -class CertificateInstance(InstanceResource): - - """ - :ivar sid: Contains a 34 character string that uniquely identifies this Certificate credential resource. - :ivar url: Contains an absolute URL for this Certificate credential resource. - :ivar friendly_name: Contains a human readable descriptive text for this Certificate credential, up to 256 characters long. - :ivar fleet_sid: Specifies the unique string identifier of the Fleet that the given Certificate credential belongs to. - :ivar account_sid: Specifies the unique string identifier of the Account responsible for this Certificate credential. - :ivar device_sid: Specifies the unique string identifier of a Device authenticated with this Certificate credential. - :ivar thumbprint: Contains a unique hash of the payload of this Certificate credential, used to authenticate the Device. - :ivar date_created: Specifies the date this Certificate credential was created, given in UTC ISO 8601 format. - :ivar date_updated: Specifies the date this Certificate credential was last updated, given in UTC ISO 8601 format. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - fleet_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.url: Optional[str] = payload.get("url") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.fleet_sid: Optional[str] = payload.get("fleet_sid") - self.account_sid: Optional[str] = payload.get("account_sid") - self.device_sid: Optional[str] = payload.get("device_sid") - self.thumbprint: Optional[str] = payload.get("thumbprint") - 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 = { - "fleet_sid": fleet_sid, - "sid": sid or self.sid, - } - self._context: Optional[CertificateContext] = None - - @property - def _proxy(self) -> "CertificateContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: CertificateContext for this CertificateInstance - """ - if self._context is None: - self._context = CertificateContext( - self._version, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the CertificateInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the CertificateInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "CertificateInstance": - """ - Fetch the CertificateInstance - - - :returns: The fetched CertificateInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "CertificateInstance": - """ - Asynchronous coroutine to fetch the CertificateInstance - - - :returns: The fetched CertificateInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> "CertificateInstance": - """ - Update the CertificateInstance - - :param friendly_name: Provides a human readable descriptive text for this Certificate credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Certificate credential. - - :returns: The updated CertificateInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - device_sid=device_sid, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> "CertificateInstance": - """ - Asynchronous coroutine to update the CertificateInstance - - :param friendly_name: Provides a human readable descriptive text for this Certificate credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Certificate credential. - - :returns: The updated CertificateInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - device_sid=device_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 CertificateContext(InstanceContext): - def __init__(self, version: Version, fleet_sid: str, sid: str): - """ - Initialize the CertificateContext - - :param version: Version that contains the resource - :param fleet_sid: - :param sid: Provides a 34 character string that uniquely identifies the requested Certificate credential resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "fleet_sid": fleet_sid, - "sid": sid, - } - self._uri = "/Fleets/{fleet_sid}/Certificates/{sid}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the CertificateInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the CertificateInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> CertificateInstance: - """ - Fetch the CertificateInstance - - - :returns: The fetched CertificateInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return CertificateInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> CertificateInstance: - """ - Asynchronous coroutine to fetch the CertificateInstance - - - :returns: The fetched CertificateInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return CertificateInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> CertificateInstance: - """ - Update the CertificateInstance - - :param friendly_name: Provides a human readable descriptive text for this Certificate credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Certificate credential. - - :returns: The updated CertificateInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "DeviceSid": device_sid, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return CertificateInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> CertificateInstance: - """ - Asynchronous coroutine to update the CertificateInstance - - :param friendly_name: Provides a human readable descriptive text for this Certificate credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Certificate credential. - - :returns: The updated CertificateInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "DeviceSid": device_sid, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return CertificateInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_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 "".format(context) - - -class CertificatePage(Page): - def get_instance(self, payload: Dict[str, Any]) -> CertificateInstance: - """ - Build an instance of CertificateInstance - - :param payload: Payload response from the API - """ - return CertificateInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class CertificateList(ListResource): - def __init__(self, version: Version, fleet_sid: str): - """ - Initialize the CertificateList - - :param version: Version that contains the resource - :param fleet_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "fleet_sid": fleet_sid, - } - self._uri = "/Fleets/{fleet_sid}/Certificates".format(**self._solution) - - def create( - self, - certificate_data: str, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> CertificateInstance: - """ - Create the CertificateInstance - - :param certificate_data: Provides a URL encoded representation of the public certificate in PEM format. - :param friendly_name: Provides a human readable descriptive text for this Certificate credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Certificate credential. - - :returns: The created CertificateInstance - """ - data = values.of( - { - "CertificateData": certificate_data, - "FriendlyName": friendly_name, - "DeviceSid": device_sid, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return CertificateInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - async def create_async( - self, - certificate_data: str, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> CertificateInstance: - """ - Asynchronously create the CertificateInstance - - :param certificate_data: Provides a URL encoded representation of the public certificate in PEM format. - :param friendly_name: Provides a human readable descriptive text for this Certificate credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Certificate credential. - - :returns: The created CertificateInstance - """ - data = values.of( - { - "CertificateData": certificate_data, - "FriendlyName": friendly_name, - "DeviceSid": device_sid, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return CertificateInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - def stream( - self, - device_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[CertificateInstance]: - """ - Streams CertificateInstance 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 device_sid: Filters the resulting list of Certificates by a unique string identifier of an authenticated Device. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(device_sid=device_sid, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - device_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[CertificateInstance]: - """ - Asynchronously streams CertificateInstance 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 device_sid: Filters the resulting list of Certificates by a unique string identifier of an authenticated Device. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - device_sid=device_sid, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - device_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[CertificateInstance]: - """ - Lists CertificateInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str device_sid: Filters the resulting list of Certificates by a unique string identifier of an authenticated Device. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - device_sid=device_sid, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - device_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[CertificateInstance]: - """ - Asynchronously lists CertificateInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str device_sid: Filters the resulting list of Certificates by a unique string identifier of an authenticated Device. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - device_sid=device_sid, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - device_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, - ) -> CertificatePage: - """ - Retrieve a single page of CertificateInstance records from the API. - Request is executed immediately - - :param device_sid: Filters the resulting list of Certificates by a unique string identifier of an authenticated Device. - :param page_token: PageToken provided by the API - :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 CertificateInstance - """ - data = values.of( - { - "DeviceSid": device_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return CertificatePage(self._version, response, self._solution) - - async def page_async( - self, - device_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, - ) -> CertificatePage: - """ - Asynchronously retrieve a single page of CertificateInstance records from the API. - Request is executed immediately - - :param device_sid: Filters the resulting list of Certificates by a unique string identifier of an authenticated Device. - :param page_token: PageToken provided by the API - :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 CertificateInstance - """ - data = values.of( - { - "DeviceSid": device_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return CertificatePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> CertificatePage: - """ - Retrieve a specific page of CertificateInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of CertificateInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return CertificatePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> CertificatePage: - """ - Asynchronously retrieve a specific page of CertificateInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of CertificateInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return CertificatePage(self._version, response, self._solution) - - def get(self, sid: str) -> CertificateContext: - """ - Constructs a CertificateContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Certificate credential resource. - """ - return CertificateContext( - self._version, fleet_sid=self._solution["fleet_sid"], sid=sid - ) - - def __call__(self, sid: str) -> CertificateContext: - """ - Constructs a CertificateContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Certificate credential resource. - """ - return CertificateContext( - self._version, fleet_sid=self._solution["fleet_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/deployed_devices/fleet/deployment.py b/twilio/rest/preview/deployed_devices/fleet/deployment.py deleted file mode 100644 index 5dbda65c66..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/deployment.py +++ /dev/null @@ -1,629 +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 - - -class DeploymentInstance(InstanceResource): - - """ - :ivar sid: Contains a 34 character string that uniquely identifies this Deployment resource. - :ivar url: Contains an absolute URL for this Deployment resource. - :ivar friendly_name: Contains a human readable descriptive text for this Deployment, up to 64 characters long - :ivar fleet_sid: Specifies the unique string identifier of the Fleet that the given Deployment belongs to. - :ivar account_sid: Specifies the unique string identifier of the Account responsible for this Deployment. - :ivar sync_service_sid: Specifies the unique string identifier of the Twilio Sync service instance linked to and accessible by this Deployment. - :ivar date_created: Specifies the date this Deployment was created, given in UTC ISO 8601 format. - :ivar date_updated: Specifies the date this Deployment was last updated, given in UTC ISO 8601 format. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - fleet_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.url: Optional[str] = payload.get("url") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.fleet_sid: Optional[str] = payload.get("fleet_sid") - self.account_sid: Optional[str] = payload.get("account_sid") - self.sync_service_sid: Optional[str] = payload.get("sync_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._solution = { - "fleet_sid": fleet_sid, - "sid": sid or self.sid, - } - self._context: Optional[DeploymentContext] = None - - @property - def _proxy(self) -> "DeploymentContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DeploymentContext for this DeploymentInstance - """ - if self._context is None: - self._context = DeploymentContext( - self._version, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the DeploymentInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeploymentInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "DeploymentInstance": - """ - Fetch the DeploymentInstance - - - :returns: The fetched DeploymentInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DeploymentInstance": - """ - Asynchronous coroutine to fetch the DeploymentInstance - - - :returns: The fetched DeploymentInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - friendly_name: Union[str, object] = values.unset, - sync_service_sid: Union[str, object] = values.unset, - ) -> "DeploymentInstance": - """ - Update the DeploymentInstance - - :param friendly_name: Provides a human readable descriptive text for this Deployment, up to 64 characters long - :param sync_service_sid: Provides the unique string identifier of the Twilio Sync service instance that will be linked to and accessible by this Deployment. - - :returns: The updated DeploymentInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - sync_service_sid=sync_service_sid, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - sync_service_sid: Union[str, object] = values.unset, - ) -> "DeploymentInstance": - """ - Asynchronous coroutine to update the DeploymentInstance - - :param friendly_name: Provides a human readable descriptive text for this Deployment, up to 64 characters long - :param sync_service_sid: Provides the unique string identifier of the Twilio Sync service instance that will be linked to and accessible by this Deployment. - - :returns: The updated DeploymentInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - sync_service_sid=sync_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 "".format(context) - - -class DeploymentContext(InstanceContext): - def __init__(self, version: Version, fleet_sid: str, sid: str): - """ - Initialize the DeploymentContext - - :param version: Version that contains the resource - :param fleet_sid: - :param sid: Provides a 34 character string that uniquely identifies the requested Deployment resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "fleet_sid": fleet_sid, - "sid": sid, - } - self._uri = "/Fleets/{fleet_sid}/Deployments/{sid}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the DeploymentInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeploymentInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> DeploymentInstance: - """ - Fetch the DeploymentInstance - - - :returns: The fetched DeploymentInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return DeploymentInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> DeploymentInstance: - """ - Asynchronous coroutine to fetch the DeploymentInstance - - - :returns: The fetched DeploymentInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return DeploymentInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - sync_service_sid: Union[str, object] = values.unset, - ) -> DeploymentInstance: - """ - Update the DeploymentInstance - - :param friendly_name: Provides a human readable descriptive text for this Deployment, up to 64 characters long - :param sync_service_sid: Provides the unique string identifier of the Twilio Sync service instance that will be linked to and accessible by this Deployment. - - :returns: The updated DeploymentInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "SyncServiceSid": sync_service_sid, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return DeploymentInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - sync_service_sid: Union[str, object] = values.unset, - ) -> DeploymentInstance: - """ - Asynchronous coroutine to update the DeploymentInstance - - :param friendly_name: Provides a human readable descriptive text for this Deployment, up to 64 characters long - :param sync_service_sid: Provides the unique string identifier of the Twilio Sync service instance that will be linked to and accessible by this Deployment. - - :returns: The updated DeploymentInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "SyncServiceSid": sync_service_sid, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return DeploymentInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_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 "".format(context) - - -class DeploymentPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> DeploymentInstance: - """ - Build an instance of DeploymentInstance - - :param payload: Payload response from the API - """ - return DeploymentInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class DeploymentList(ListResource): - def __init__(self, version: Version, fleet_sid: str): - """ - Initialize the DeploymentList - - :param version: Version that contains the resource - :param fleet_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "fleet_sid": fleet_sid, - } - self._uri = "/Fleets/{fleet_sid}/Deployments".format(**self._solution) - - def create( - self, - friendly_name: Union[str, object] = values.unset, - sync_service_sid: Union[str, object] = values.unset, - ) -> DeploymentInstance: - """ - Create the DeploymentInstance - - :param friendly_name: Provides a human readable descriptive text for this Deployment, up to 256 characters long. - :param sync_service_sid: Provides the unique string identifier of the Twilio Sync service instance that will be linked to and accessible by this Deployment. - - :returns: The created DeploymentInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "SyncServiceSid": sync_service_sid, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return DeploymentInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - async def create_async( - self, - friendly_name: Union[str, object] = values.unset, - sync_service_sid: Union[str, object] = values.unset, - ) -> DeploymentInstance: - """ - Asynchronously create the DeploymentInstance - - :param friendly_name: Provides a human readable descriptive text for this Deployment, up to 256 characters long. - :param sync_service_sid: Provides the unique string identifier of the Twilio Sync service instance that will be linked to and accessible by this Deployment. - - :returns: The created DeploymentInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "SyncServiceSid": sync_service_sid, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return DeploymentInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[DeploymentInstance]: - """ - Streams DeploymentInstance 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[DeploymentInstance]: - """ - Asynchronously streams DeploymentInstance 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[DeploymentInstance]: - """ - Lists DeploymentInstance 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[DeploymentInstance]: - """ - Asynchronously lists DeploymentInstance 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, - ) -> DeploymentPage: - """ - Retrieve a single page of DeploymentInstance 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 DeploymentInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return DeploymentPage(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, - ) -> DeploymentPage: - """ - Asynchronously retrieve a single page of DeploymentInstance 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 DeploymentInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return DeploymentPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> DeploymentPage: - """ - Retrieve a specific page of DeploymentInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DeploymentInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return DeploymentPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> DeploymentPage: - """ - Asynchronously retrieve a specific page of DeploymentInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of DeploymentInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return DeploymentPage(self._version, response, self._solution) - - def get(self, sid: str) -> DeploymentContext: - """ - Constructs a DeploymentContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Deployment resource. - """ - return DeploymentContext( - self._version, fleet_sid=self._solution["fleet_sid"], sid=sid - ) - - def __call__(self, sid: str) -> DeploymentContext: - """ - Constructs a DeploymentContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Deployment resource. - """ - return DeploymentContext( - self._version, fleet_sid=self._solution["fleet_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/deployed_devices/fleet/device.py b/twilio/rest/preview/deployed_devices/fleet/device.py deleted file mode 100644 index afaa0fce2a..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/device.py +++ /dev/null @@ -1,699 +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 - - -class DeviceInstance(InstanceResource): - - """ - :ivar sid: Contains a 34 character string that uniquely identifies this Device resource. - :ivar url: Contains an absolute URL for this Device resource. - :ivar unique_name: Contains a unique and addressable name of this Device, assigned by the developer, up to 128 characters long. - :ivar friendly_name: Contains a human readable descriptive text for this Device, up to 256 characters long - :ivar fleet_sid: Specifies the unique string identifier of the Fleet that the given Device belongs to. - :ivar enabled: Contains a boolean flag indicating whether the device is enabled or not, blocks device connectivity if set to false. - :ivar account_sid: Specifies the unique string identifier of the Account responsible for this Device. - :ivar identity: Contains an arbitrary string identifier representing a human user associated with this Device, assigned by the developer, up to 256 characters long. - :ivar deployment_sid: Specifies the unique string identifier of the Deployment group that this Device is associated with. - :ivar date_created: Specifies the date this Device was created, given in UTC ISO 8601 format. - :ivar date_updated: Specifies the date this Device was last updated, given in UTC ISO 8601 format. - :ivar date_authenticated: Specifies the date this Device was last authenticated, given in UTC ISO 8601 format. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - fleet_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.url: Optional[str] = payload.get("url") - self.unique_name: Optional[str] = payload.get("unique_name") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.fleet_sid: Optional[str] = payload.get("fleet_sid") - self.enabled: Optional[bool] = payload.get("enabled") - self.account_sid: Optional[str] = payload.get("account_sid") - self.identity: Optional[str] = payload.get("identity") - self.deployment_sid: Optional[str] = payload.get("deployment_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_authenticated: Optional[datetime] = deserialize.iso8601_datetime( - payload.get("date_authenticated") - ) - - self._solution = { - "fleet_sid": fleet_sid, - "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, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the DeviceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeviceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - 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, - friendly_name: Union[str, object] = values.unset, - identity: Union[str, object] = values.unset, - deployment_sid: Union[str, object] = values.unset, - enabled: Union[bool, object] = values.unset, - ) -> "DeviceInstance": - """ - Update the DeviceInstance - - :param friendly_name: Provides a human readable descriptive text to be assigned to this Device, up to 256 characters long. - :param identity: Provides an arbitrary string identifier representing a human user to be associated with this Device, up to 256 characters long. - :param deployment_sid: Specifies the unique string identifier of the Deployment group that this Device is going to be associated with. - :param enabled: - - :returns: The updated DeviceInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - identity=identity, - deployment_sid=deployment_sid, - enabled=enabled, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - identity: Union[str, object] = values.unset, - deployment_sid: Union[str, object] = values.unset, - enabled: Union[bool, object] = values.unset, - ) -> "DeviceInstance": - """ - Asynchronous coroutine to update the DeviceInstance - - :param friendly_name: Provides a human readable descriptive text to be assigned to this Device, up to 256 characters long. - :param identity: Provides an arbitrary string identifier representing a human user to be associated with this Device, up to 256 characters long. - :param deployment_sid: Specifies the unique string identifier of the Deployment group that this Device is going to be associated with. - :param enabled: - - :returns: The updated DeviceInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - identity=identity, - deployment_sid=deployment_sid, - enabled=enabled, - ) - - 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 DeviceContext(InstanceContext): - def __init__(self, version: Version, fleet_sid: str, sid: str): - """ - Initialize the DeviceContext - - :param version: Version that contains the resource - :param fleet_sid: - :param sid: Provides a 34 character string that uniquely identifies the requested Device resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "fleet_sid": fleet_sid, - "sid": sid, - } - self._uri = "/Fleets/{fleet_sid}/Devices/{sid}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the DeviceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DeviceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> DeviceInstance: - """ - Fetch the DeviceInstance - - - :returns: The fetched DeviceInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return DeviceInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> DeviceInstance: - """ - Asynchronous coroutine to fetch the DeviceInstance - - - :returns: The fetched DeviceInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return DeviceInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - identity: Union[str, object] = values.unset, - deployment_sid: Union[str, object] = values.unset, - enabled: Union[bool, object] = values.unset, - ) -> DeviceInstance: - """ - Update the DeviceInstance - - :param friendly_name: Provides a human readable descriptive text to be assigned to this Device, up to 256 characters long. - :param identity: Provides an arbitrary string identifier representing a human user to be associated with this Device, up to 256 characters long. - :param deployment_sid: Specifies the unique string identifier of the Deployment group that this Device is going to be associated with. - :param enabled: - - :returns: The updated DeviceInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "Identity": identity, - "DeploymentSid": deployment_sid, - "Enabled": enabled, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return DeviceInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - identity: Union[str, object] = values.unset, - deployment_sid: Union[str, object] = values.unset, - enabled: Union[bool, object] = values.unset, - ) -> DeviceInstance: - """ - Asynchronous coroutine to update the DeviceInstance - - :param friendly_name: Provides a human readable descriptive text to be assigned to this Device, up to 256 characters long. - :param identity: Provides an arbitrary string identifier representing a human user to be associated with this Device, up to 256 characters long. - :param deployment_sid: Specifies the unique string identifier of the Deployment group that this Device is going to be associated with. - :param enabled: - - :returns: The updated DeviceInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "Identity": identity, - "DeploymentSid": deployment_sid, - "Enabled": enabled, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return DeviceInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_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 "".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, fleet_sid=self._solution["fleet_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class DeviceList(ListResource): - def __init__(self, version: Version, fleet_sid: str): - """ - Initialize the DeviceList - - :param version: Version that contains the resource - :param fleet_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "fleet_sid": fleet_sid, - } - self._uri = "/Fleets/{fleet_sid}/Devices".format(**self._solution) - - def create( - self, - unique_name: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, - identity: Union[str, object] = values.unset, - deployment_sid: Union[str, object] = values.unset, - enabled: Union[bool, object] = values.unset, - ) -> DeviceInstance: - """ - Create the DeviceInstance - - :param unique_name: Provides a unique and addressable name to be assigned to this Device, to be used in addition to SID, up to 128 characters long. - :param friendly_name: Provides a human readable descriptive text to be assigned to this Device, up to 256 characters long. - :param identity: Provides an arbitrary string identifier representing a human user to be associated with this Device, up to 256 characters long. - :param deployment_sid: Specifies the unique string identifier of the Deployment group that this Device is going to be associated with. - :param enabled: - - :returns: The created DeviceInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - "Identity": identity, - "DeploymentSid": deployment_sid, - "Enabled": enabled, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return DeviceInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - async def create_async( - self, - unique_name: Union[str, object] = values.unset, - friendly_name: Union[str, object] = values.unset, - identity: Union[str, object] = values.unset, - deployment_sid: Union[str, object] = values.unset, - enabled: Union[bool, object] = values.unset, - ) -> DeviceInstance: - """ - Asynchronously create the DeviceInstance - - :param unique_name: Provides a unique and addressable name to be assigned to this Device, to be used in addition to SID, up to 128 characters long. - :param friendly_name: Provides a human readable descriptive text to be assigned to this Device, up to 256 characters long. - :param identity: Provides an arbitrary string identifier representing a human user to be associated with this Device, up to 256 characters long. - :param deployment_sid: Specifies the unique string identifier of the Deployment group that this Device is going to be associated with. - :param enabled: - - :returns: The created DeviceInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - "Identity": identity, - "DeploymentSid": deployment_sid, - "Enabled": enabled, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return DeviceInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - def stream( - self, - deployment_sid: Union[str, object] = values.unset, - 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 str deployment_sid: Filters the resulting list of Devices by a unique string identifier of the Deployment they are associated with. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(deployment_sid=deployment_sid, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - deployment_sid: Union[str, object] = values.unset, - 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 str deployment_sid: Filters the resulting list of Devices by a unique string identifier of the Deployment they are associated with. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - deployment_sid=deployment_sid, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - deployment_sid: Union[str, object] = values.unset, - 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 str deployment_sid: Filters the resulting list of Devices by a unique string identifier of the Deployment they are associated with. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - deployment_sid=deployment_sid, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - deployment_sid: Union[str, object] = values.unset, - 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 str deployment_sid: Filters the resulting list of Devices by a unique string identifier of the Deployment they are associated with. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - deployment_sid=deployment_sid, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - deployment_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, - ) -> DevicePage: - """ - Retrieve a single page of DeviceInstance records from the API. - Request is executed immediately - - :param deployment_sid: Filters the resulting list of Devices by a unique string identifier of the Deployment they are associated with. - :param page_token: PageToken provided by the API - :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( - { - "DeploymentSid": deployment_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return DevicePage(self._version, response, self._solution) - - async def page_async( - self, - deployment_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, - ) -> DevicePage: - """ - Asynchronously retrieve a single page of DeviceInstance records from the API. - Request is executed immediately - - :param deployment_sid: Filters the resulting list of Devices by a unique string identifier of the Deployment they are associated with. - :param page_token: PageToken provided by the API - :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( - { - "DeploymentSid": deployment_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return DevicePage(self._version, response, self._solution) - - 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, self._solution) - - 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, self._solution) - - def get(self, sid: str) -> DeviceContext: - """ - Constructs a DeviceContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Device resource. - """ - return DeviceContext( - self._version, fleet_sid=self._solution["fleet_sid"], sid=sid - ) - - def __call__(self, sid: str) -> DeviceContext: - """ - Constructs a DeviceContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Device resource. - """ - return DeviceContext( - self._version, fleet_sid=self._solution["fleet_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/deployed_devices/fleet/key.py b/twilio/rest/preview/deployed_devices/fleet/key.py deleted file mode 100644 index 9bcfd8fb0f..0000000000 --- a/twilio/rest/preview/deployed_devices/fleet/key.py +++ /dev/null @@ -1,645 +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 - - -class KeyInstance(InstanceResource): - - """ - :ivar sid: Contains a 34 character string that uniquely identifies this Key credential resource. - :ivar url: Contains an absolute URL for this Key credential resource. - :ivar friendly_name: Contains a human readable descriptive text for this Key credential, up to 256 characters long. - :ivar fleet_sid: Specifies the unique string identifier of the Fleet that the given Key credential belongs to. - :ivar account_sid: Specifies the unique string identifier of the Account responsible for this Key credential. - :ivar device_sid: Specifies the unique string identifier of a Device authenticated with this Key credential. - :ivar secret: Contains the automatically generated secret belonging to this Key credential, used to authenticate the Device. - :ivar date_created: Specifies the date this Key credential was created, given in UTC ISO 8601 format. - :ivar date_updated: Specifies the date this Key credential was last updated, given in UTC ISO 8601 format. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - fleet_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.sid: Optional[str] = payload.get("sid") - self.url: Optional[str] = payload.get("url") - self.friendly_name: Optional[str] = payload.get("friendly_name") - self.fleet_sid: Optional[str] = payload.get("fleet_sid") - self.account_sid: Optional[str] = payload.get("account_sid") - self.device_sid: Optional[str] = payload.get("device_sid") - self.secret: Optional[str] = payload.get("secret") - 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 = { - "fleet_sid": fleet_sid, - "sid": sid or self.sid, - } - self._context: Optional[KeyContext] = None - - @property - def _proxy(self) -> "KeyContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: KeyContext for this KeyInstance - """ - if self._context is None: - self._context = KeyContext( - self._version, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the KeyInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the KeyInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "KeyInstance": - """ - Fetch the KeyInstance - - - :returns: The fetched KeyInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "KeyInstance": - """ - Asynchronous coroutine to fetch the KeyInstance - - - :returns: The fetched KeyInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> "KeyInstance": - """ - Update the KeyInstance - - :param friendly_name: Provides a human readable descriptive text for this Key credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Key credential. - - :returns: The updated KeyInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - device_sid=device_sid, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> "KeyInstance": - """ - Asynchronous coroutine to update the KeyInstance - - :param friendly_name: Provides a human readable descriptive text for this Key credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Key credential. - - :returns: The updated KeyInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - device_sid=device_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 KeyContext(InstanceContext): - def __init__(self, version: Version, fleet_sid: str, sid: str): - """ - Initialize the KeyContext - - :param version: Version that contains the resource - :param fleet_sid: - :param sid: Provides a 34 character string that uniquely identifies the requested Key credential resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "fleet_sid": fleet_sid, - "sid": sid, - } - self._uri = "/Fleets/{fleet_sid}/Keys/{sid}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the KeyInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the KeyInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> KeyInstance: - """ - Fetch the KeyInstance - - - :returns: The fetched KeyInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return KeyInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> KeyInstance: - """ - Asynchronous coroutine to fetch the KeyInstance - - - :returns: The fetched KeyInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return KeyInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> KeyInstance: - """ - Update the KeyInstance - - :param friendly_name: Provides a human readable descriptive text for this Key credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Key credential. - - :returns: The updated KeyInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "DeviceSid": device_sid, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return KeyInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> KeyInstance: - """ - Asynchronous coroutine to update the KeyInstance - - :param friendly_name: Provides a human readable descriptive text for this Key credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Key credential. - - :returns: The updated KeyInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "DeviceSid": device_sid, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return KeyInstance( - self._version, - payload, - fleet_sid=self._solution["fleet_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 "".format(context) - - -class KeyPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> KeyInstance: - """ - Build an instance of KeyInstance - - :param payload: Payload response from the API - """ - return KeyInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class KeyList(ListResource): - def __init__(self, version: Version, fleet_sid: str): - """ - Initialize the KeyList - - :param version: Version that contains the resource - :param fleet_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "fleet_sid": fleet_sid, - } - self._uri = "/Fleets/{fleet_sid}/Keys".format(**self._solution) - - def create( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> KeyInstance: - """ - Create the KeyInstance - - :param friendly_name: Provides a human readable descriptive text for this Key credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Key credential. - - :returns: The created KeyInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "DeviceSid": device_sid, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return KeyInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - async def create_async( - self, - friendly_name: Union[str, object] = values.unset, - device_sid: Union[str, object] = values.unset, - ) -> KeyInstance: - """ - Asynchronously create the KeyInstance - - :param friendly_name: Provides a human readable descriptive text for this Key credential, up to 256 characters long. - :param device_sid: Provides the unique string identifier of an existing Device to become authenticated with this Key credential. - - :returns: The created KeyInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "DeviceSid": device_sid, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return KeyInstance( - self._version, payload, fleet_sid=self._solution["fleet_sid"] - ) - - def stream( - self, - device_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[KeyInstance]: - """ - Streams KeyInstance 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 device_sid: Filters the resulting list of Keys by a unique string identifier of an authenticated Device. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(device_sid=device_sid, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - device_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[KeyInstance]: - """ - Asynchronously streams KeyInstance 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 device_sid: Filters the resulting list of Keys by a unique string identifier of an authenticated Device. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - device_sid=device_sid, page_size=limits["page_size"] - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - device_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[KeyInstance]: - """ - Lists KeyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str device_sid: Filters the resulting list of Keys by a unique string identifier of an authenticated Device. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - device_sid=device_sid, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - device_sid: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[KeyInstance]: - """ - Asynchronously lists KeyInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str device_sid: Filters the resulting list of Keys by a unique string identifier of an authenticated Device. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - device_sid=device_sid, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - device_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, - ) -> KeyPage: - """ - Retrieve a single page of KeyInstance records from the API. - Request is executed immediately - - :param device_sid: Filters the resulting list of Keys by a unique string identifier of an authenticated Device. - :param page_token: PageToken provided by the API - :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 KeyInstance - """ - data = values.of( - { - "DeviceSid": device_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return KeyPage(self._version, response, self._solution) - - async def page_async( - self, - device_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, - ) -> KeyPage: - """ - Asynchronously retrieve a single page of KeyInstance records from the API. - Request is executed immediately - - :param device_sid: Filters the resulting list of Keys by a unique string identifier of an authenticated Device. - :param page_token: PageToken provided by the API - :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 KeyInstance - """ - data = values.of( - { - "DeviceSid": device_sid, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return KeyPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> KeyPage: - """ - Retrieve a specific page of KeyInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of KeyInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return KeyPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> KeyPage: - """ - Asynchronously retrieve a specific page of KeyInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of KeyInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return KeyPage(self._version, response, self._solution) - - def get(self, sid: str) -> KeyContext: - """ - Constructs a KeyContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Key credential resource. - """ - return KeyContext(self._version, fleet_sid=self._solution["fleet_sid"], sid=sid) - - def __call__(self, sid: str) -> KeyContext: - """ - Constructs a KeyContext - - :param sid: Provides a 34 character string that uniquely identifies the requested Key credential resource. - """ - return KeyContext(self._version, fleet_sid=self._solution["fleet_sid"], sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/hosted_numbers/__init__.py b/twilio/rest/preview/hosted_numbers/__init__.py index fd46160426..7b3a767eef 100644 --- a/twilio/rest/preview/hosted_numbers/__init__.py +++ b/twilio/rest/preview/hosted_numbers/__init__.py @@ -22,6 +22,7 @@ class HostedNumbers(Version): + def __init__(self, domain: Domain): """ Initialize the HostedNumbers version of Preview diff --git a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py index 8d04498859..27ff55c37d 100644 --- a/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py +++ b/twilio/rest/preview/hosted_numbers/authorization_document/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,6 +27,7 @@ class AuthorizationDocumentInstance(InstanceResource): + class Status(object): OPENED = "opened" SIGNING = "signing" @@ -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: """ @@ -191,12 +277,13 @@ def __repr__(self) -> str: class AuthorizationDocumentContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the AuthorizationDocumentContext :param version: Version that contains the resource - :param sid: + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. """ super().__init__(version) @@ -210,6 +297,22 @@ def __init__(self, version: Version, sid: str): DependentHostedNumberOrderList ] = None + 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) -> AuthorizationDocumentInstance: """ Fetch the AuthorizationDocumentInstance @@ -217,17 +320,43 @@ def fetch(self) -> AuthorizationDocumentInstance: :returns: The fetched AuthorizationDocumentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AuthorizationDocumentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AuthorizationDocumentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AuthorizationDocumentInstance: """ @@ -236,19 +365,29 @@ async def fetch_async(self) -> AuthorizationDocumentInstance: :returns: The fetched AuthorizationDocumentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AuthorizationDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AuthorizationDocumentInstance( + 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( + def _update( self, hosted_number_order_sids: Union[List[str], object] = values.unset, address_sid: Union[str, object] = values.unset, @@ -257,20 +396,14 @@ 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( { "HostedNumberOrderSids": serialize.map( @@ -284,18 +417,53 @@ def update( "ContactPhoneNumber": contact_phone_number, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -304,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. @@ -316,8 +484,39 @@ 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( { "HostedNumberOrderSids": serialize.map( @@ -331,17 +530,89 @@ async def update_async( "ContactPhoneNumber": contact_phone_number, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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: """ @@ -367,12 +638,14 @@ def __repr__(self) -> str: class AuthorizationDocumentPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AuthorizationDocumentInstance: """ Build an instance of AuthorizationDocumentInstance :param payload: Payload response from the API """ + return AuthorizationDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -385,6 +658,7 @@ def __repr__(self) -> str: class AuthorizationDocumentList(ListResource): + def __init__(self, version: Version): """ Initialize the AuthorizationDocumentList @@ -396,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, @@ -404,19 +678,14 @@ def create( contact_title: str, contact_phone_number: str, cc_emails: Union[List[str], object] = values.unset, - ) -> AuthorizationDocumentInstance: + ) -> tuple: """ - Create the AuthorizationDocumentInstance + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "HostedNumberOrderSids": serialize.map( @@ -429,16 +698,17 @@ def create( "CcEmails": serialize.map(cc_emails, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AuthorizationDocumentInstance(self._version, payload) + headers["Accept"] = "application/json" - async def create_async( + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( self, hosted_number_order_sids: List[str], address_sid: str, @@ -448,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. @@ -459,6 +729,64 @@ 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( { "HostedNumberOrderSids": serialize.map( @@ -471,15 +799,79 @@ async def create_async( "CcEmails": serialize.map(cc_emails, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -494,7 +886,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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 @@ -523,7 +915,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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 @@ -540,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, @@ -553,7 +1005,7 @@ def list( memory before returning. :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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 @@ -563,6 +1015,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( email=email, @@ -585,7 +1038,7 @@ async def list_async( memory before returning. :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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 @@ -595,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( @@ -605,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, @@ -618,7 +1134,7 @@ def page( Request is executed immediately :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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 @@ -635,7 +1151,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 AuthorizationDocumentPage(self._version, response) async def page_async( @@ -651,7 +1173,7 @@ async def page_async( Request is executed immediately :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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 @@ -668,11 +1190,97 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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. @@ -701,7 +1309,7 @@ def get(self, sid: str) -> AuthorizationDocumentContext: """ Constructs a AuthorizationDocumentContext - :param sid: + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. """ return AuthorizationDocumentContext(self._version, sid=sid) @@ -709,7 +1317,7 @@ def __call__(self, sid: str) -> AuthorizationDocumentContext: """ Constructs a AuthorizationDocumentContext - :param sid: + :param sid: A 34 character string that uniquely identifies this AuthorizationDocument. """ return AuthorizationDocumentContext(self._version, sid=sid) 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 836c06fd99..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 @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,7 +24,9 @@ class DependentHostedNumberOrderInstance(InstanceResource): + class Status(object): + TWILIO_PROCESSING = "twilio-processing" RECEIVED = "received" PENDING_VERIFICATION = "pending-verification" VERIFIED = "verified" @@ -80,9 +82,9 @@ def __init__( self.capabilities: Optional[str] = payload.get("capabilities") self.friendly_name: Optional[str] = payload.get("friendly_name") self.unique_name: Optional[str] = payload.get("unique_name") - self.status: Optional[ - "DependentHostedNumberOrderInstance.Status" - ] = payload.get("status") + self.status: Optional["DependentHostedNumberOrderInstance.Status"] = ( + payload.get("status") + ) self.failure_reason: Optional[str] = payload.get("failure_reason") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") @@ -125,6 +127,7 @@ def __repr__(self) -> str: class DependentHostedNumberOrderPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> DependentHostedNumberOrderInstance: @@ -133,6 +136,7 @@ def get_instance( :param payload: Payload response from the API """ + return DependentHostedNumberOrderInstance( self._version, payload, @@ -149,12 +153,13 @@ def __repr__(self) -> str: class DependentHostedNumberOrderList(ListResource): + def __init__(self, version: Version, signing_document_sid: str): """ Initialize the DependentHostedNumberOrderList :param version: Version that contains the resource - :param signing_document_sid: + :param signing_document_sid: A 34 character string that uniquely identifies the LOA document associated with this HostedNumberOrder. """ super().__init__(version) @@ -185,7 +190,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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. @@ -229,7 +234,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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. @@ -255,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[ @@ -272,7 +363,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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. @@ -286,6 +377,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -315,7 +407,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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. @@ -329,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( @@ -342,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[ @@ -359,7 +536,7 @@ def page( Retrieve a single page of DependentHostedNumberOrderInstance records from the API. Request is executed immediately - :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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. @@ -383,8 +560,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DependentHostedNumberOrderPage(self._version, response, self._solution) + 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 DependentHostedNumberOrderPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -403,7 +588,7 @@ async def page_async( Asynchronously retrieve a single page of DependentHostedNumberOrderInstance records from the API. Request is executed immediately - :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/api/phone-numbers/hosted-number-authorization-documents#status-values) for more information on each of these statuses. + :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. @@ -427,10 +612,124 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + return DependentHostedNumberOrderPage( + self._version, response, solution=self._solution ) - return DependentHostedNumberOrderPage(self._version, response, 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: """ @@ -442,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: """ @@ -454,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 1c34e99769..1b26c1b53b 100644 --- a/twilio/rest/preview/hosted_numbers/hosted_number_order.py +++ b/twilio/rest/preview/hosted_numbers/hosted_number_order.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,9 @@ class HostedNumberOrderInstance(InstanceResource): + class Status(object): + TWILIO_PROCESSING = "twilio-processing" RECEIVED = "received" PENDING_VERIFICATION = "pending-verification" VERIFIED = "verified" @@ -42,9 +44,9 @@ class VerificationType(object): """ :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/api/rest/incoming-phone-numbers) resource that represents the phone number being hosted. + :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/api/phone-numbers/hosted-number-authorization-documents) the user needs to sign. + :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. @@ -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 @@ -267,12 +394,13 @@ def __repr__(self) -> str: class HostedNumberOrderContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the HostedNumberOrderContext :param version: Version that contains the resource - :param sid: + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. """ super().__init__(version) @@ -282,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 @@ -289,9 +431,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -301,9 +465,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the HostedNumberOrderInstance 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) -> HostedNumberOrderInstance: @@ -313,17 +501,43 @@ def fetch(self) -> HostedNumberOrderInstance: :returns: The fetched HostedNumberOrderInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return HostedNumberOrderInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the HostedNumberOrderInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> HostedNumberOrderInstance: """ @@ -332,19 +546,29 @@ async def fetch_async(self) -> HostedNumberOrderInstance: :returns: The fetched HostedNumberOrderInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return HostedNumberOrderInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return HostedNumberOrderInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, unique_name: Union[str, object] = values.unset, @@ -358,23 +582,14 @@ 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( { "FriendlyName": friendly_name, @@ -389,18 +604,64 @@ def update( "CallDelay": call_delay, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -414,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. @@ -429,8 +690,47 @@ 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( { "FriendlyName": friendly_name, @@ -445,17 +745,111 @@ async def update_async( "CallDelay": call_delay, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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, + 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 @@ -469,12 +863,14 @@ def __repr__(self) -> str: class HostedNumberOrderPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance: """ Build an instance of HostedNumberOrderInstance :param payload: Payload response from the API """ + return HostedNumberOrderInstance(self._version, payload) def __repr__(self) -> str: @@ -487,6 +883,7 @@ def __repr__(self) -> str: class HostedNumberOrderList(ListResource): + def __init__(self, version: Version): """ Initialize the HostedNumberOrderList @@ -498,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, @@ -543,10 +1000,127 @@ 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( { "PhoneNumber": phone_number, - "SmsCapability": sms_capability, + "SmsCapability": serialize.boolean_to_string(sms_capability), "AccountSid": account_sid, "FriendlyName": friendly_name, "UniqueName": unique_name, @@ -564,16 +1138,83 @@ def create( "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. - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + :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_async( + async def create_with_http_info_async( self, phone_number: str, sms_capability: bool, @@ -594,9 +1235,9 @@ async def create_async( "HostedNumberOrderInstance.VerificationType", object ] = values.unset, verification_document_sid: Union[str, object] = values.unset, - ) -> HostedNumberOrderInstance: + ) -> ApiResponse: """ - Asynchronously create the HostedNumberOrderInstance + 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. @@ -616,37 +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": 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, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, @@ -732,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, @@ -761,6 +1476,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -802,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( @@ -815,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, @@ -854,7 +1651,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 HostedNumberOrderPage(self._version, response) async def page_async( @@ -896,11 +1699,115 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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. @@ -929,7 +1836,7 @@ def get(self, sid: str) -> HostedNumberOrderContext: """ Constructs a HostedNumberOrderContext - :param sid: + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. """ return HostedNumberOrderContext(self._version, sid=sid) @@ -937,7 +1844,7 @@ def __call__(self, sid: str) -> HostedNumberOrderContext: """ Constructs a HostedNumberOrderContext - :param sid: + :param sid: A 34 character string that uniquely identifies this HostedNumberOrder. """ return HostedNumberOrderContext(self._version, sid=sid) diff --git a/twilio/rest/preview/marketplace/__init__.py b/twilio/rest/preview/marketplace/__init__.py index d12d3ab0a5..fcc99a4112 100644 --- a/twilio/rest/preview/marketplace/__init__.py +++ b/twilio/rest/preview/marketplace/__init__.py @@ -20,6 +20,7 @@ class Marketplace(Version): + def __init__(self, domain: Domain): """ Initialize the Marketplace version of Preview diff --git a/twilio/rest/preview/marketplace/available_add_on/__init__.py b/twilio/rest/preview/marketplace/available_add_on/__init__.py index 776a33e9d9..76fc06a367 100644 --- a/twilio/rest/preview/marketplace/available_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/available_add_on/__init__.py @@ -12,9 +12,9 @@ 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 @@ -26,7 +26,6 @@ class AvailableAddOnInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the AvailableAddOn resource. :ivar friendly_name: The string that you assigned to describe the resource. @@ -55,6 +54,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnContext] = None @property @@ -90,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: """ @@ -108,6 +126,7 @@ def __repr__(self) -> str: class AvailableAddOnContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the AvailableAddOnContext @@ -125,6 +144,22 @@ def __init__(self, version: Version, sid: str): self._extensions: Optional[AvailableAddOnExtensionList] = None + 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) -> AvailableAddOnInstance: """ Fetch the AvailableAddOnInstance @@ -132,17 +167,43 @@ def fetch(self) -> AvailableAddOnInstance: :returns: The fetched AvailableAddOnInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AvailableAddOnInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AvailableAddOnInstance: """ @@ -151,17 +212,27 @@ async def fetch_async(self) -> AvailableAddOnInstance: :returns: The fetched AvailableAddOnInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AvailableAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return AvailableAddOnInstance( + 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: @@ -186,12 +257,14 @@ def __repr__(self) -> str: class AvailableAddOnPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnInstance: """ Build an instance of AvailableAddOnInstance :param payload: Payload response from the API """ + return AvailableAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -204,6 +277,7 @@ def __repr__(self) -> str: class AvailableAddOnList(ListResource): + def __init__(self, version: Version): """ Initialize the AvailableAddOnList @@ -265,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, @@ -284,6 +408,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -310,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( @@ -318,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, @@ -342,7 +518,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 AvailableAddOnPage(self._version, response) async def page_async( @@ -369,11 +551,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 218b48ee3f..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 @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class AvailableAddOnExtensionInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the AvailableAddOnExtension resource. :ivar available_add_on_sid: The SID of the AvailableAddOn resource to which this extension applies. @@ -53,6 +52,7 @@ def __init__( "available_add_on_sid": available_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[AvailableAddOnExtensionContext] = None @property @@ -89,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 @@ -102,6 +120,7 @@ def __repr__(self) -> str: class AvailableAddOnExtensionContext(InstanceContext): + def __init__(self, version: Version, available_add_on_sid: str, sid: str): """ Initialize the AvailableAddOnExtensionContext @@ -121,6 +140,22 @@ def __init__(self, version: Version, available_add_on_sid: str, sid: str): **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) -> AvailableAddOnExtensionInstance: """ Fetch the AvailableAddOnExtensionInstance @@ -128,18 +163,45 @@ def fetch(self) -> AvailableAddOnExtensionInstance: :returns: The fetched AvailableAddOnExtensionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], ) - return AvailableAddOnExtensionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AvailableAddOnExtensionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AvailableAddOnExtensionInstance: """ @@ -148,18 +210,29 @@ async def fetch_async(self) -> AvailableAddOnExtensionInstance: :returns: The fetched AvailableAddOnExtensionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AvailableAddOnExtensionInstance( + self._version, + payload, + available_add_on_sid=self._solution["available_add_on_sid"], + sid=self._solution["sid"], ) - return AvailableAddOnExtensionInstance( + 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: """ @@ -174,12 +247,14 @@ def __repr__(self) -> str: class AvailableAddOnExtensionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AvailableAddOnExtensionInstance: """ Build an instance of AvailableAddOnExtensionInstance :param payload: Payload response from the API """ + return AvailableAddOnExtensionInstance( self._version, payload, @@ -196,6 +271,7 @@ def __repr__(self) -> str: class AvailableAddOnExtensionList(ListResource): + def __init__(self, version: Version, available_add_on_sid: str): """ Initialize the AvailableAddOnExtensionList @@ -264,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, @@ -283,6 +409,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -309,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( @@ -317,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, @@ -341,8 +519,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + 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 AvailableAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -368,10 +554,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return AvailableAddOnExtensionPage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Accept"] = "application/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: """ @@ -383,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: """ @@ -395,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 87d0926728..c7352ed699 100644 --- a/twilio/rest/preview/marketplace/installed_add_on/__init__.py +++ b/twilio/rest/preview/marketplace/installed_add_on/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class InstalledAddOnInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the InstalledAddOn resource. This Sid can also be found in the Console on that specific Add-ons page as the 'Available Add-on Sid'. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the InstalledAddOn resource. @@ -64,6 +63,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnContext] = None @property @@ -99,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 @@ -117,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, @@ -153,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: """ @@ -171,6 +243,7 @@ def __repr__(self) -> str: class InstalledAddOnContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the InstalledAddOnContext @@ -188,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 @@ -195,9 +282,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -207,9 +316,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InstalledAddOnInstance 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) -> InstalledAddOnInstance: @@ -219,17 +352,43 @@ def fetch(self) -> InstalledAddOnInstance: :returns: The fetched InstalledAddOnInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return InstalledAddOnInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> InstalledAddOnInstance: """ @@ -238,17 +397,55 @@ async def fetch_async(self) -> InstalledAddOnInstance: :returns: The fetched InstalledAddOnInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return InstalledAddOnInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return InstalledAddOnInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Configuration": serialize.object(configuration), + "UniqueName": unique_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, @@ -263,20 +460,59 @@ def update( :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( { "Configuration": serialize.object(configuration), "UniqueName": unique_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -291,20 +527,31 @@ async def update_async( :returns: The updated InstalledAddOnInstance """ - data = values.of( - { - "Configuration": serialize.object(configuration), - "UniqueName": unique_name, - } + payload, _, _ = await self._update_async( + configuration=configuration, unique_name=unique_name ) + return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return InstalledAddOnInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -329,12 +576,14 @@ def __repr__(self) -> str: class InstalledAddOnPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnInstance: """ Build an instance of InstalledAddOnInstance :param payload: Payload response from the API """ + return InstalledAddOnInstance(self._version, payload) def __repr__(self) -> str: @@ -347,6 +596,7 @@ def __repr__(self) -> str: class InstalledAddOnList(ListResource): + def __init__(self, version: Version): """ Initialize the InstalledAddOnList @@ -358,6 +608,40 @@ def __init__(self, version: Version): self._uri = "/InstalledAddOns" + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "AvailableAddOnSid": available_add_on_sid, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), + "Configuration": serialize.object(configuration), + "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" + + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, available_add_on_sid: str, @@ -375,22 +659,73 @@ def create( :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( { "AvailableAddOnSid": available_add_on_sid, - "AcceptTermsOfService": accept_terms_of_service, + "AcceptTermsOfService": serialize.boolean_to_string( + accept_terms_of_service + ), "Configuration": serialize.object(configuration), "UniqueName": unique_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return InstalledAddOnInstance(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, @@ -409,22 +744,39 @@ async def create_async( :returns: The created InstalledAddOnInstance """ - data = values.of( - { - "AvailableAddOnSid": available_add_on_sid, - "AcceptTermsOfService": accept_terms_of_service, - "Configuration": serialize.object(configuration), - "UniqueName": unique_name, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return InstalledAddOnInstance(self._version, payload) + :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, @@ -476,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, @@ -495,6 +897,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -521,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( @@ -529,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, @@ -553,7 +1007,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 InstalledAddOnPage(self._version, response) async def page_async( @@ -580,11 +1040,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 e191c8c48f..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 @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import values +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 @@ -23,7 +23,6 @@ class InstalledAddOnExtensionInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the InstalledAddOn Extension resource. :ivar installed_add_on_sid: The SID of the InstalledAddOn resource to which this extension applies. @@ -55,6 +54,7 @@ def __init__( "installed_add_on_sid": installed_add_on_sid, "sid": sid or self.sid, } + self._context: Optional[InstalledAddOnExtensionContext] = None @property @@ -91,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 @@ -115,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 @@ -128,6 +170,7 @@ def __repr__(self) -> str: class InstalledAddOnExtensionContext(InstanceContext): + def __init__(self, version: Version, installed_add_on_sid: str, sid: str): """ Initialize the InstalledAddOnExtensionContext @@ -147,6 +190,22 @@ def __init__(self, version: Version, installed_add_on_sid: str, sid: str): **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) -> InstalledAddOnExtensionInstance: """ Fetch the InstalledAddOnExtensionInstance @@ -154,18 +213,45 @@ def fetch(self) -> InstalledAddOnExtensionInstance: :returns: The fetched InstalledAddOnExtensionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return InstalledAddOnExtensionInstance( + self._version, + payload, + installed_add_on_sid=self._solution["installed_add_on_sid"], + sid=self._solution["sid"], ) - return InstalledAddOnExtensionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InstalledAddOnExtensionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> InstalledAddOnExtensionInstance: """ @@ -174,12 +260,7 @@ async def fetch_async(self) -> InstalledAddOnExtensionInstance: :returns: The fetched InstalledAddOnExtensionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return InstalledAddOnExtensionInstance( self._version, payload, @@ -187,26 +268,54 @@ 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( { - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -214,26 +323,55 @@ 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( { - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -241,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 @@ -254,12 +409,14 @@ def __repr__(self) -> str: class InstalledAddOnExtensionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InstalledAddOnExtensionInstance: """ Build an instance of InstalledAddOnExtensionInstance :param payload: Payload response from the API """ + return InstalledAddOnExtensionInstance( self._version, payload, @@ -276,6 +433,7 @@ def __repr__(self) -> str: class InstalledAddOnExtensionList(ListResource): + def __init__(self, version: Version, installed_add_on_sid: str): """ Initialize the InstalledAddOnExtensionList @@ -344,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, @@ -363,6 +571,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -389,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( @@ -397,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, @@ -421,8 +681,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + 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 InstalledAddOnExtensionPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -448,10 +716,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 ) - return InstalledAddOnExtensionPage(self._version, response, self._solution) + 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: """ @@ -463,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: """ @@ -475,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 c9f33d19bf..0000000000 --- a/twilio/rest/preview/sync/service/__init__.py +++ /dev/null @@ -1,700 +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.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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ServiceInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> ServiceInstance: - """ - Fetch the ServiceInstance - - - :returns: The fetched ServiceInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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": reachability_webhooks_enabled, - "AclEnabled": acl_enabled, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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": reachability_webhooks_enabled, - "AclEnabled": acl_enabled, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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": reachability_webhooks_enabled, - "AclEnabled": acl_enabled, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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": reachability_webhooks_enabled, - "AclEnabled": acl_enabled, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 ebd08889f9..0000000000 --- a/twilio/rest/preview/sync/service/document/__init__.py +++ /dev/null @@ -1,656 +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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DocumentInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> DocumentInstance: - """ - Fetch the DocumentInstance - - - :returns: The fetched DocumentInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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-Match": if_match, - } - ) - - 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-Match": if_match, - } - ) - - 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 "".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 "" - - -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), - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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), - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 1b43dc9fcf..0000000000 --- a/twilio/rest/preview/sync/service/document/document_permission.py +++ /dev/null @@ -1,592 +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 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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the DocumentPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> DocumentPermissionInstance: - """ - Fetch the DocumentPermissionInstance - - - :returns: The fetched DocumentPermissionInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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": read, - "Write": write, - "Manage": manage, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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": read, - "Write": write, - "Manage": manage, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 d3cd34c547..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/__init__.py +++ /dev/null @@ -1,570 +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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncListInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> SyncListInstance: - """ - Fetch the SyncListInstance - - - :returns: The fetched SyncListInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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 "".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 "" - - -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, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 592f84a3c4..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_item.py +++ /dev/null @@ -1,722 +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 "".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, - } - ) - - 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, - } - ) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> SyncListItemInstance: - """ - Fetch the SyncListItemInstance - - - :returns: The fetched SyncListItemInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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-Match": if_match, - } - ) - - 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-Match": if_match, - } - ) - - 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 "".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 "" - - -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), - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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), - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 7e1a2db968..0000000000 --- a/twilio/rest/preview/sync/service/sync_list/sync_list_permission.py +++ /dev/null @@ -1,592 +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 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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncListPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> SyncListPermissionInstance: - """ - Fetch the SyncListPermissionInstance - - - :returns: The fetched SyncListPermissionInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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": read, - "Write": write, - "Manage": manage, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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": read, - "Write": write, - "Manage": manage, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 47235fd80c..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/__init__.py +++ /dev/null @@ -1,568 +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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncMapInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> SyncMapInstance: - """ - Fetch the SyncMapInstance - - - :returns: The fetched SyncMapInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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 "".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 "" - - -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, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 ef42e77d38..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_item.py +++ /dev/null @@ -1,726 +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 "".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, - } - ) - - 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, - } - ) - - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers - ) - - def fetch(self) -> SyncMapItemInstance: - """ - Fetch the SyncMapItemInstance - - - :returns: The fetched SyncMapItemInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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-Match": if_match, - } - ) - - 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-Match": if_match, - } - ) - - 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 "".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 "" - - -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), - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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), - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" 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 3b3230fe17..0000000000 --- a/twilio/rest/preview/sync/service/sync_map/sync_map_permission.py +++ /dev/null @@ -1,590 +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 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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SyncMapPermissionInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> SyncMapPermissionInstance: - """ - Fetch the SyncMapPermissionInstance - - - :returns: The fetched SyncMapPermissionInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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": read, - "Write": write, - "Manage": manage, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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": read, - "Write": write, - "Manage": manage, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" diff --git a/twilio/rest/preview/understand/assistant/__init__.py b/twilio/rest/preview/understand/assistant/__init__.py deleted file mode 100644 index 27970ca4da..0000000000 --- a/twilio/rest/preview/understand/assistant/__init__.py +++ /dev/null @@ -1,887 +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.understand.assistant.assistant_fallback_actions import ( - AssistantFallbackActionsList, -) -from twilio.rest.preview.understand.assistant.assistant_initiation_actions import ( - AssistantInitiationActionsList, -) -from twilio.rest.preview.understand.assistant.dialogue import DialogueList -from twilio.rest.preview.understand.assistant.field_type import FieldTypeList -from twilio.rest.preview.understand.assistant.model_build import ModelBuildList -from twilio.rest.preview.understand.assistant.query import QueryList -from twilio.rest.preview.understand.assistant.style_sheet import StyleSheetList -from twilio.rest.preview.understand.assistant.task import TaskList - - -class AssistantInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Assistant. - :ivar date_created: The date that this resource was created - :ivar date_updated: The date that this resource was last updated - :ivar friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :ivar latest_model_build_sid: The unique ID (Sid) of the latest model build. Null if no model has been built. - :ivar links: - :ivar log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. - :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. You can use the unique name in the URL path. Unique up to 64 characters long. - :ivar url: - :ivar callback_url: A user-provided URL to send event callbacks to. - :ivar callback_events: Space-separated list of callback events that will trigger callbacks. - """ - - def __init__( - self, version: Version, payload: Dict[str, Any], sid: Optional[str] = None - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.friendly_name: Optional[str] = payload.get("friendly_name") - self.latest_model_build_sid: Optional[str] = payload.get( - "latest_model_build_sid" - ) - self.links: Optional[Dict[str, object]] = payload.get("links") - self.log_queries: Optional[bool] = payload.get("log_queries") - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.url: Optional[str] = payload.get("url") - self.callback_url: Optional[str] = payload.get("callback_url") - self.callback_events: Optional[str] = payload.get("callback_events") - - self._solution = { - "sid": sid or self.sid, - } - 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, - sid=self._solution["sid"], - ) - 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, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - fallback_actions: Union[object, object] = values.unset, - initiation_actions: Union[object, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - ) -> "AssistantInstance": - """ - Update the AssistantInstance - - :param friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :param log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. Defaults to true if no value is provided. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param callback_url: A user-provided URL to send event callbacks to. - :param callback_events: Space-separated list of callback events that will trigger callbacks. - :param fallback_actions: The JSON actions to be executed when the user's input is not recognized as matching any Task. - :param initiation_actions: The JSON actions to be executed on inbound phone calls when the Assistant has to say something first. - :param style_sheet: The JSON object that holds the style sheet for the assistant - - :returns: The updated AssistantInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - log_queries=log_queries, - unique_name=unique_name, - callback_url=callback_url, - callback_events=callback_events, - fallback_actions=fallback_actions, - initiation_actions=initiation_actions, - style_sheet=style_sheet, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - fallback_actions: Union[object, object] = values.unset, - initiation_actions: Union[object, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - ) -> "AssistantInstance": - """ - Asynchronous coroutine to update the AssistantInstance - - :param friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :param log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. Defaults to true if no value is provided. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param callback_url: A user-provided URL to send event callbacks to. - :param callback_events: Space-separated list of callback events that will trigger callbacks. - :param fallback_actions: The JSON actions to be executed when the user's input is not recognized as matching any Task. - :param initiation_actions: The JSON actions to be executed on inbound phone calls when the Assistant has to say something first. - :param style_sheet: The JSON object that holds the style sheet for the assistant - - :returns: The updated AssistantInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - log_queries=log_queries, - unique_name=unique_name, - callback_url=callback_url, - callback_events=callback_events, - fallback_actions=fallback_actions, - initiation_actions=initiation_actions, - style_sheet=style_sheet, - ) - - @property - def assistant_fallback_actions(self) -> AssistantFallbackActionsList: - """ - Access the assistant_fallback_actions - """ - return self._proxy.assistant_fallback_actions - - @property - def assistant_initiation_actions(self) -> AssistantInitiationActionsList: - """ - Access the assistant_initiation_actions - """ - return self._proxy.assistant_initiation_actions - - @property - def dialogues(self) -> DialogueList: - """ - Access the dialogues - """ - return self._proxy.dialogues - - @property - def field_types(self) -> FieldTypeList: - """ - Access the field_types - """ - return self._proxy.field_types - - @property - def model_builds(self) -> ModelBuildList: - """ - Access the model_builds - """ - return self._proxy.model_builds - - @property - def queries(self) -> QueryList: - """ - Access the queries - """ - return self._proxy.queries - - @property - def style_sheet(self) -> StyleSheetList: - """ - Access the style_sheet - """ - return self._proxy.style_sheet - - @property - def tasks(self) -> TaskList: - """ - Access the tasks - """ - return self._proxy.tasks - - 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): - def __init__(self, version: Version, sid: str): - """ - Initialize the AssistantContext - - :param version: Version that contains the resource - :param sid: A 34 character string that uniquely identifies this resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "sid": sid, - } - self._uri = "/Assistants/{sid}".format(**self._solution) - - self._assistant_fallback_actions: Optional[AssistantFallbackActionsList] = None - self._assistant_initiation_actions: Optional[ - AssistantInitiationActionsList - ] = None - self._dialogues: Optional[DialogueList] = None - self._field_types: Optional[FieldTypeList] = None - self._model_builds: Optional[ModelBuildList] = None - self._queries: Optional[QueryList] = None - self._style_sheet: Optional[StyleSheetList] = None - self._tasks: Optional[TaskList] = None - - def delete(self) -> bool: - """ - Deletes the AssistantInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the AssistantInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> AssistantInstance: - """ - Fetch the AssistantInstance - - - :returns: The fetched AssistantInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return AssistantInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> AssistantInstance: - """ - Asynchronous coroutine to fetch the AssistantInstance - - - :returns: The fetched AssistantInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return AssistantInstance( - self._version, - payload, - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - fallback_actions: Union[object, object] = values.unset, - initiation_actions: Union[object, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - ) -> AssistantInstance: - """ - Update the AssistantInstance - - :param friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :param log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. Defaults to true if no value is provided. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param callback_url: A user-provided URL to send event callbacks to. - :param callback_events: Space-separated list of callback events that will trigger callbacks. - :param fallback_actions: The JSON actions to be executed when the user's input is not recognized as matching any Task. - :param initiation_actions: The JSON actions to be executed on inbound phone calls when the Assistant has to say something first. - :param style_sheet: The JSON object that holds the style sheet for the assistant - - :returns: The updated AssistantInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "LogQueries": log_queries, - "UniqueName": unique_name, - "CallbackUrl": callback_url, - "CallbackEvents": callback_events, - "FallbackActions": serialize.object(fallback_actions), - "InitiationActions": serialize.object(initiation_actions), - "StyleSheet": serialize.object(style_sheet), - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantInstance(self._version, payload, sid=self._solution["sid"]) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - fallback_actions: Union[object, object] = values.unset, - initiation_actions: Union[object, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - ) -> AssistantInstance: - """ - Asynchronous coroutine to update the AssistantInstance - - :param friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :param log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. Defaults to true if no value is provided. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param callback_url: A user-provided URL to send event callbacks to. - :param callback_events: Space-separated list of callback events that will trigger callbacks. - :param fallback_actions: The JSON actions to be executed when the user's input is not recognized as matching any Task. - :param initiation_actions: The JSON actions to be executed on inbound phone calls when the Assistant has to say something first. - :param style_sheet: The JSON object that holds the style sheet for the assistant - - :returns: The updated AssistantInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "LogQueries": log_queries, - "UniqueName": unique_name, - "CallbackUrl": callback_url, - "CallbackEvents": callback_events, - "FallbackActions": serialize.object(fallback_actions), - "InitiationActions": serialize.object(initiation_actions), - "StyleSheet": serialize.object(style_sheet), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def assistant_fallback_actions(self) -> AssistantFallbackActionsList: - """ - Access the assistant_fallback_actions - """ - if self._assistant_fallback_actions is None: - self._assistant_fallback_actions = AssistantFallbackActionsList( - self._version, - self._solution["sid"], - ) - return self._assistant_fallback_actions - - @property - def assistant_initiation_actions(self) -> AssistantInitiationActionsList: - """ - Access the assistant_initiation_actions - """ - if self._assistant_initiation_actions is None: - self._assistant_initiation_actions = AssistantInitiationActionsList( - self._version, - self._solution["sid"], - ) - return self._assistant_initiation_actions - - @property - def dialogues(self) -> DialogueList: - """ - Access the dialogues - """ - if self._dialogues is None: - self._dialogues = DialogueList( - self._version, - self._solution["sid"], - ) - return self._dialogues - - @property - def field_types(self) -> FieldTypeList: - """ - Access the field_types - """ - if self._field_types is None: - self._field_types = FieldTypeList( - self._version, - self._solution["sid"], - ) - return self._field_types - - @property - def model_builds(self) -> ModelBuildList: - """ - Access the model_builds - """ - if self._model_builds is None: - self._model_builds = ModelBuildList( - self._version, - self._solution["sid"], - ) - return self._model_builds - - @property - def queries(self) -> QueryList: - """ - Access the queries - """ - if self._queries is None: - self._queries = QueryList( - self._version, - self._solution["sid"], - ) - return self._queries - - @property - def style_sheet(self) -> StyleSheetList: - """ - Access the style_sheet - """ - if self._style_sheet is None: - self._style_sheet = StyleSheetList( - self._version, - self._solution["sid"], - ) - return self._style_sheet - - @property - def tasks(self) -> TaskList: - """ - Access the tasks - """ - if self._tasks is None: - self._tasks = TaskList( - self._version, - self._solution["sid"], - ) - return self._tasks - - 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): - def __init__(self, version: Version): - """ - Initialize the AssistantList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/Assistants" - - def create( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - fallback_actions: Union[object, object] = values.unset, - initiation_actions: Union[object, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - ) -> AssistantInstance: - """ - Create the AssistantInstance - - :param friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :param log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. Defaults to true if no value is provided. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param callback_url: A user-provided URL to send event callbacks to. - :param callback_events: Space-separated list of callback events that will trigger callbacks. - :param fallback_actions: The JSON actions to be executed when the user's input is not recognized as matching any Task. - :param initiation_actions: The JSON actions to be executed on inbound phone calls when the Assistant has to say something first. - :param style_sheet: The JSON object that holds the style sheet for the assistant - - :returns: The created AssistantInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "LogQueries": log_queries, - "UniqueName": unique_name, - "CallbackUrl": callback_url, - "CallbackEvents": callback_events, - "FallbackActions": serialize.object(fallback_actions), - "InitiationActions": serialize.object(initiation_actions), - "StyleSheet": serialize.object(style_sheet), - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantInstance(self._version, payload) - - async def create_async( - self, - friendly_name: Union[str, object] = values.unset, - log_queries: Union[bool, object] = values.unset, - unique_name: Union[str, object] = values.unset, - callback_url: Union[str, object] = values.unset, - callback_events: Union[str, object] = values.unset, - fallback_actions: Union[object, object] = values.unset, - initiation_actions: Union[object, object] = values.unset, - style_sheet: Union[object, object] = values.unset, - ) -> AssistantInstance: - """ - Asynchronously create the AssistantInstance - - :param friendly_name: A text description for the Assistant. It is non-unique and can up to 255 characters long. - :param log_queries: A boolean that specifies whether queries should be logged for 30 days further training. If false, no queries will be stored, if true, queries will be stored for 30 days and deleted thereafter. Defaults to true if no value is provided. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param callback_url: A user-provided URL to send event callbacks to. - :param callback_events: Space-separated list of callback events that will trigger callbacks. - :param fallback_actions: The JSON actions to be executed when the user's input is not recognized as matching any Task. - :param initiation_actions: The JSON actions to be executed on inbound phone calls when the Assistant has to say something first. - :param style_sheet: The JSON object that holds the style sheet for the assistant - - :returns: The created AssistantInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "LogQueries": log_queries, - "UniqueName": unique_name, - "CallbackUrl": callback_url, - "CallbackEvents": callback_events, - "FallbackActions": serialize.object(fallback_actions), - "InitiationActions": serialize.object(initiation_actions), - "StyleSheet": serialize.object(style_sheet), - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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, sid: str) -> AssistantContext: - """ - Constructs a AssistantContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return AssistantContext(self._version, sid=sid) - - def __call__(self, sid: str) -> AssistantContext: - """ - Constructs a AssistantContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return AssistantContext(self._version, sid=sid) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/assistant_fallback_actions.py b/twilio/rest/preview/understand/assistant/assistant_fallback_actions.py deleted file mode 100644 index 84e964de0e..0000000000 --- a/twilio/rest/preview/understand/assistant/assistant_fallback_actions.py +++ /dev/null @@ -1,279 +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, Optional, Union -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 - - -class AssistantFallbackActionsInstance(InstanceResource): - - """ - :ivar account_sid: - :ivar assistant_sid: - :ivar url: - :ivar data: - """ - - def __init__(self, version: Version, payload: Dict[str, Any], assistant_sid: str): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.url: Optional[str] = payload.get("url") - self.data: Optional[Dict[str, object]] = payload.get("data") - - self._solution = { - "assistant_sid": assistant_sid, - } - self._context: Optional[AssistantFallbackActionsContext] = None - - @property - def _proxy(self) -> "AssistantFallbackActionsContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: AssistantFallbackActionsContext for this AssistantFallbackActionsInstance - """ - if self._context is None: - self._context = AssistantFallbackActionsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - ) - return self._context - - def fetch(self) -> "AssistantFallbackActionsInstance": - """ - Fetch the AssistantFallbackActionsInstance - - - :returns: The fetched AssistantFallbackActionsInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "AssistantFallbackActionsInstance": - """ - Asynchronous coroutine to fetch the AssistantFallbackActionsInstance - - - :returns: The fetched AssistantFallbackActionsInstance - """ - return await self._proxy.fetch_async() - - def update( - self, fallback_actions: Union[object, object] = values.unset - ) -> "AssistantFallbackActionsInstance": - """ - Update the AssistantFallbackActionsInstance - - :param fallback_actions: - - :returns: The updated AssistantFallbackActionsInstance - """ - return self._proxy.update( - fallback_actions=fallback_actions, - ) - - async def update_async( - self, fallback_actions: Union[object, object] = values.unset - ) -> "AssistantFallbackActionsInstance": - """ - Asynchronous coroutine to update the AssistantFallbackActionsInstance - - :param fallback_actions: - - :returns: The updated AssistantFallbackActionsInstance - """ - return await self._proxy.update_async( - fallback_actions=fallback_actions, - ) - - 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 AssistantFallbackActionsContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the AssistantFallbackActionsContext - - :param version: Version that contains the resource - :param assistant_sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/FallbackActions".format( - **self._solution - ) - - def fetch(self) -> AssistantFallbackActionsInstance: - """ - Fetch the AssistantFallbackActionsInstance - - - :returns: The fetched AssistantFallbackActionsInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return AssistantFallbackActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - async def fetch_async(self) -> AssistantFallbackActionsInstance: - """ - Asynchronous coroutine to fetch the AssistantFallbackActionsInstance - - - :returns: The fetched AssistantFallbackActionsInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return AssistantFallbackActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - def update( - self, fallback_actions: Union[object, object] = values.unset - ) -> AssistantFallbackActionsInstance: - """ - Update the AssistantFallbackActionsInstance - - :param fallback_actions: - - :returns: The updated AssistantFallbackActionsInstance - """ - data = values.of( - { - "FallbackActions": serialize.object(fallback_actions), - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantFallbackActionsInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def update_async( - self, fallback_actions: Union[object, object] = values.unset - ) -> AssistantFallbackActionsInstance: - """ - Asynchronous coroutine to update the AssistantFallbackActionsInstance - - :param fallback_actions: - - :returns: The updated AssistantFallbackActionsInstance - """ - data = values.of( - { - "FallbackActions": serialize.object(fallback_actions), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantFallbackActionsInstance( - self._version, payload, assistant_sid=self._solution["assistant_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 AssistantFallbackActionsList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the AssistantFallbackActionsList - - :param version: Version that contains the resource - :param assistant_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - - def get(self) -> AssistantFallbackActionsContext: - """ - Constructs a AssistantFallbackActionsContext - - """ - return AssistantFallbackActionsContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __call__(self) -> AssistantFallbackActionsContext: - """ - Constructs a AssistantFallbackActionsContext - - """ - return AssistantFallbackActionsContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/assistant_initiation_actions.py b/twilio/rest/preview/understand/assistant/assistant_initiation_actions.py deleted file mode 100644 index 544154f658..0000000000 --- a/twilio/rest/preview/understand/assistant/assistant_initiation_actions.py +++ /dev/null @@ -1,283 +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, Optional, Union -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 - - -class AssistantInitiationActionsInstance(InstanceResource): - - """ - :ivar account_sid: - :ivar assistant_sid: - :ivar url: - :ivar data: - """ - - def __init__(self, version: Version, payload: Dict[str, Any], assistant_sid: str): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.url: Optional[str] = payload.get("url") - self.data: Optional[Dict[str, object]] = payload.get("data") - - self._solution = { - "assistant_sid": assistant_sid, - } - self._context: Optional[AssistantInitiationActionsContext] = None - - @property - def _proxy(self) -> "AssistantInitiationActionsContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: AssistantInitiationActionsContext for this AssistantInitiationActionsInstance - """ - if self._context is None: - self._context = AssistantInitiationActionsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - ) - return self._context - - def fetch(self) -> "AssistantInitiationActionsInstance": - """ - Fetch the AssistantInitiationActionsInstance - - - :returns: The fetched AssistantInitiationActionsInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "AssistantInitiationActionsInstance": - """ - Asynchronous coroutine to fetch the AssistantInitiationActionsInstance - - - :returns: The fetched AssistantInitiationActionsInstance - """ - return await self._proxy.fetch_async() - - def update( - self, initiation_actions: Union[object, object] = values.unset - ) -> "AssistantInitiationActionsInstance": - """ - Update the AssistantInitiationActionsInstance - - :param initiation_actions: - - :returns: The updated AssistantInitiationActionsInstance - """ - return self._proxy.update( - initiation_actions=initiation_actions, - ) - - async def update_async( - self, initiation_actions: Union[object, object] = values.unset - ) -> "AssistantInitiationActionsInstance": - """ - Asynchronous coroutine to update the AssistantInitiationActionsInstance - - :param initiation_actions: - - :returns: The updated AssistantInitiationActionsInstance - """ - return await self._proxy.update_async( - initiation_actions=initiation_actions, - ) - - 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 AssistantInitiationActionsContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the AssistantInitiationActionsContext - - :param version: Version that contains the resource - :param assistant_sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/InitiationActions".format( - **self._solution - ) - - def fetch(self) -> AssistantInitiationActionsInstance: - """ - Fetch the AssistantInitiationActionsInstance - - - :returns: The fetched AssistantInitiationActionsInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return AssistantInitiationActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - async def fetch_async(self) -> AssistantInitiationActionsInstance: - """ - Asynchronous coroutine to fetch the AssistantInitiationActionsInstance - - - :returns: The fetched AssistantInitiationActionsInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return AssistantInitiationActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - def update( - self, initiation_actions: Union[object, object] = values.unset - ) -> AssistantInitiationActionsInstance: - """ - Update the AssistantInitiationActionsInstance - - :param initiation_actions: - - :returns: The updated AssistantInitiationActionsInstance - """ - data = values.of( - { - "InitiationActions": serialize.object(initiation_actions), - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantInitiationActionsInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def update_async( - self, initiation_actions: Union[object, object] = values.unset - ) -> AssistantInitiationActionsInstance: - """ - Asynchronous coroutine to update the AssistantInitiationActionsInstance - - :param initiation_actions: - - :returns: The updated AssistantInitiationActionsInstance - """ - data = values.of( - { - "InitiationActions": serialize.object(initiation_actions), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return AssistantInitiationActionsInstance( - self._version, payload, assistant_sid=self._solution["assistant_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 AssistantInitiationActionsList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the AssistantInitiationActionsList - - :param version: Version that contains the resource - :param assistant_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - - def get(self) -> AssistantInitiationActionsContext: - """ - Constructs a AssistantInitiationActionsContext - - """ - return AssistantInitiationActionsContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __call__(self) -> AssistantInitiationActionsContext: - """ - Constructs a AssistantInitiationActionsContext - - """ - return AssistantInitiationActionsContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/dialogue.py b/twilio/rest/preview/understand/assistant/dialogue.py deleted file mode 100644 index 57b0016ec2..0000000000 --- a/twilio/rest/preview/understand/assistant/dialogue.py +++ /dev/null @@ -1,210 +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, Optional -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 DialogueInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Field. - :ivar assistant_sid: The unique ID of the parent Assistant. - :ivar sid: The unique ID of the Dialogue - :ivar data: The dialogue memory object as json - :ivar url: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.data: Optional[Dict[str, object]] = payload.get("data") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[DialogueContext] = None - - @property - def _proxy(self) -> "DialogueContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: DialogueContext for this DialogueInstance - """ - if self._context is None: - self._context = DialogueContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def fetch(self) -> "DialogueInstance": - """ - Fetch the DialogueInstance - - - :returns: The fetched DialogueInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "DialogueInstance": - """ - Asynchronous coroutine to fetch the DialogueInstance - - - :returns: The fetched DialogueInstance - """ - 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 "".format(context) - - -class DialogueContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the DialogueContext - - :param version: Version that contains the resource - :param assistant_sid: - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Dialogues/{sid}".format( - **self._solution - ) - - def fetch(self) -> DialogueInstance: - """ - Fetch the DialogueInstance - - - :returns: The fetched DialogueInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return DialogueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> DialogueInstance: - """ - Asynchronous coroutine to fetch the DialogueInstance - - - :returns: The fetched DialogueInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return DialogueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_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 "".format(context) - - -class DialogueList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the DialogueList - - :param version: Version that contains the resource - :param assistant_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - - def get(self, sid: str) -> DialogueContext: - """ - Constructs a DialogueContext - - :param sid: - """ - return DialogueContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> DialogueContext: - """ - Constructs a DialogueContext - - :param sid: - """ - return DialogueContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/field_type/__init__.py b/twilio/rest/preview/understand/assistant/field_type/__init__.py deleted file mode 100644 index 0deb38faf1..0000000000 --- a/twilio/rest/preview/understand/assistant/field_type/__init__.py +++ /dev/null @@ -1,654 +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.understand.assistant.field_type.field_value import ( - FieldValueList, -) - - -class FieldTypeInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Field Type. - :ivar date_created: The date that this resource was created - :ivar date_updated: The date that this resource was last updated - :ivar friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :ivar links: - :ivar assistant_sid: The unique ID of the Assistant. - :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :ivar url: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.friendly_name: Optional[str] = payload.get("friendly_name") - self.links: Optional[Dict[str, object]] = payload.get("links") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[FieldTypeContext] = None - - @property - def _proxy(self) -> "FieldTypeContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FieldTypeContext for this FieldTypeInstance - """ - if self._context is None: - self._context = FieldTypeContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the FieldTypeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldTypeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "FieldTypeInstance": - """ - Fetch the FieldTypeInstance - - - :returns: The fetched FieldTypeInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "FieldTypeInstance": - """ - Asynchronous coroutine to fetch the FieldTypeInstance - - - :returns: The fetched FieldTypeInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> "FieldTypeInstance": - """ - Update the FieldTypeInstance - - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - - :returns: The updated FieldTypeInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> "FieldTypeInstance": - """ - Asynchronous coroutine to update the FieldTypeInstance - - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - - :returns: The updated FieldTypeInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - unique_name=unique_name, - ) - - @property - def field_values(self) -> FieldValueList: - """ - Access the field_values - """ - return self._proxy.field_values - - 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 FieldTypeContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the FieldTypeContext - - :param version: Version that contains the resource - :param assistant_sid: - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/FieldTypes/{sid}".format( - **self._solution - ) - - self._field_values: Optional[FieldValueList] = None - - def delete(self) -> bool: - """ - Deletes the FieldTypeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldTypeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> FieldTypeInstance: - """ - Fetch the FieldTypeInstance - - - :returns: The fetched FieldTypeInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> FieldTypeInstance: - """ - Asynchronous coroutine to fetch the FieldTypeInstance - - - :returns: The fetched FieldTypeInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> FieldTypeInstance: - """ - Update the FieldTypeInstance - - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - - :returns: The updated FieldTypeInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> FieldTypeInstance: - """ - Asynchronous coroutine to update the FieldTypeInstance - - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - - :returns: The updated FieldTypeInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldTypeInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - @property - def field_values(self) -> FieldValueList: - """ - Access the field_values - """ - if self._field_values is None: - self._field_values = FieldValueList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._field_values - - 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 FieldTypePage(Page): - def get_instance(self, payload: Dict[str, Any]) -> FieldTypeInstance: - """ - Build an instance of FieldTypeInstance - - :param payload: Payload response from the API - """ - return FieldTypeInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class FieldTypeList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the FieldTypeList - - :param version: Version that contains the resource - :param assistant_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/FieldTypes".format(**self._solution) - - def create( - self, unique_name: str, friendly_name: Union[str, object] = values.unset - ) -> FieldTypeInstance: - """ - Create the FieldTypeInstance - - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - - :returns: The created FieldTypeInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldTypeInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def create_async( - self, unique_name: str, friendly_name: Union[str, object] = values.unset - ) -> FieldTypeInstance: - """ - Asynchronously create the FieldTypeInstance - - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - - :returns: The created FieldTypeInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldTypeInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[FieldTypeInstance]: - """ - Streams FieldTypeInstance 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[FieldTypeInstance]: - """ - Asynchronously streams FieldTypeInstance 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[FieldTypeInstance]: - """ - Lists FieldTypeInstance 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[FieldTypeInstance]: - """ - Asynchronously lists FieldTypeInstance 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, - ) -> FieldTypePage: - """ - Retrieve a single page of FieldTypeInstance 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 FieldTypeInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return FieldTypePage(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, - ) -> FieldTypePage: - """ - Asynchronously retrieve a single page of FieldTypeInstance 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 FieldTypeInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return FieldTypePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> FieldTypePage: - """ - Retrieve a specific page of FieldTypeInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldTypeInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return FieldTypePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> FieldTypePage: - """ - Asynchronously retrieve a specific page of FieldTypeInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldTypeInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return FieldTypePage(self._version, response, self._solution) - - def get(self, sid: str) -> FieldTypeContext: - """ - Constructs a FieldTypeContext - - :param sid: - """ - return FieldTypeContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> FieldTypeContext: - """ - Constructs a FieldTypeContext - - :param sid: - """ - return FieldTypeContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/field_type/field_value.py b/twilio/rest/preview/understand/assistant/field_type/field_value.py deleted file mode 100644 index 87fb7df94b..0000000000 --- a/twilio/rest/preview/understand/assistant/field_type/field_value.py +++ /dev/null @@ -1,577 +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 - - -class FieldValueInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Field Value. - :ivar date_created: The date that this resource was created - :ivar date_updated: The date that this resource was last updated - :ivar field_type_sid: The unique ID of the Field Type associated with this Field Value. - :ivar language: An ISO language-country string of the value. - :ivar assistant_sid: The unique ID of the Assistant. - :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar value: The Field Value itself. - :ivar url: - :ivar synonym_of: A value that indicates this field value is a synonym of. Empty if the value is not a synonym. - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - field_type_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.field_type_sid: Optional[str] = payload.get("field_type_sid") - self.language: Optional[str] = payload.get("language") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.value: Optional[str] = payload.get("value") - self.url: Optional[str] = payload.get("url") - self.synonym_of: Optional[str] = payload.get("synonym_of") - - self._solution = { - "assistant_sid": assistant_sid, - "field_type_sid": field_type_sid, - "sid": sid or self.sid, - } - self._context: Optional[FieldValueContext] = None - - @property - def _proxy(self) -> "FieldValueContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FieldValueContext for this FieldValueInstance - """ - if self._context is None: - self._context = FieldValueContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the FieldValueInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldValueInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "FieldValueInstance": - """ - Fetch the FieldValueInstance - - - :returns: The fetched FieldValueInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "FieldValueInstance": - """ - Asynchronous coroutine to fetch the FieldValueInstance - - - :returns: The fetched FieldValueInstance - """ - 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 "".format(context) - - -class FieldValueContext(InstanceContext): - def __init__( - self, version: Version, assistant_sid: str, field_type_sid: str, sid: str - ): - """ - Initialize the FieldValueContext - - :param version: Version that contains the resource - :param assistant_sid: - :param field_type_sid: - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "field_type_sid": field_type_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/FieldTypes/{field_type_sid}/FieldValues/{sid}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the FieldValueInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldValueInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> FieldValueInstance: - """ - Fetch the FieldValueInstance - - - :returns: The fetched FieldValueInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> FieldValueInstance: - """ - Asynchronous coroutine to fetch the FieldValueInstance - - - :returns: The fetched FieldValueInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_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 "".format(context) - - -class FieldValuePage(Page): - def get_instance(self, payload: Dict[str, Any]) -> FieldValueInstance: - """ - Build an instance of FieldValueInstance - - :param payload: Payload response from the API - """ - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class FieldValueList(ListResource): - def __init__(self, version: Version, assistant_sid: str, field_type_sid: str): - """ - Initialize the FieldValueList - - :param version: Version that contains the resource - :param assistant_sid: - :param field_type_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "field_type_sid": field_type_sid, - } - self._uri = "/Assistants/{assistant_sid}/FieldTypes/{field_type_sid}/FieldValues".format( - **self._solution - ) - - def create( - self, language: str, value: str, synonym_of: Union[str, object] = values.unset - ) -> FieldValueInstance: - """ - Create the FieldValueInstance - - :param language: An ISO language-country string of the value. - :param value: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param synonym_of: A value that indicates this field value is a synonym of. Empty if the value is not a synonym. - - :returns: The created FieldValueInstance - """ - data = values.of( - { - "Language": language, - "Value": value, - "SynonymOf": synonym_of, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - ) - - async def create_async( - self, language: str, value: str, synonym_of: Union[str, object] = values.unset - ) -> FieldValueInstance: - """ - Asynchronously create the FieldValueInstance - - :param language: An ISO language-country string of the value. - :param value: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param synonym_of: A value that indicates this field value is a synonym of. Empty if the value is not a synonym. - - :returns: The created FieldValueInstance - """ - data = values.of( - { - "Language": language, - "Value": value, - "SynonymOf": synonym_of, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldValueInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - ) - - def stream( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[FieldValueInstance]: - """ - Streams FieldValueInstance 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 language: An ISO language-country string of the value. For example: *en-US* - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(language=language, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[FieldValueInstance]: - """ - Asynchronously streams FieldValueInstance 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 language: An ISO language-country string of the value. For example: *en-US* - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(language=language, page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[FieldValueInstance]: - """ - Lists FieldValueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: An ISO language-country string of the value. For example: *en-US* - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[FieldValueInstance]: - """ - Asynchronously lists FieldValueInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: An ISO language-country string of the value. For example: *en-US* - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - language: 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, - ) -> FieldValuePage: - """ - Retrieve a single page of FieldValueInstance records from the API. - Request is executed immediately - - :param language: An ISO language-country string of the value. For example: *en-US* - :param page_token: PageToken provided by the API - :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 FieldValueInstance - """ - data = values.of( - { - "Language": language, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return FieldValuePage(self._version, response, self._solution) - - async def page_async( - self, - language: 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, - ) -> FieldValuePage: - """ - Asynchronously retrieve a single page of FieldValueInstance records from the API. - Request is executed immediately - - :param language: An ISO language-country string of the value. For example: *en-US* - :param page_token: PageToken provided by the API - :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 FieldValueInstance - """ - data = values.of( - { - "Language": language, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return FieldValuePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> FieldValuePage: - """ - Retrieve a specific page of FieldValueInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldValueInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return FieldValuePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> FieldValuePage: - """ - Asynchronously retrieve a specific page of FieldValueInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldValueInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return FieldValuePage(self._version, response, self._solution) - - def get(self, sid: str) -> FieldValueContext: - """ - Constructs a FieldValueContext - - :param sid: - """ - return FieldValueContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - sid=sid, - ) - - def __call__(self, sid: str) -> FieldValueContext: - """ - Constructs a FieldValueContext - - :param sid: - """ - return FieldValueContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - field_type_sid=self._solution["field_type_sid"], - sid=sid, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/model_build.py b/twilio/rest/preview/understand/assistant/model_build.py deleted file mode 100644 index 8b45b76dc0..0000000000 --- a/twilio/rest/preview/understand/assistant/model_build.py +++ /dev/null @@ -1,627 +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 - - -class ModelBuildInstance(InstanceResource): - class Status(object): - ENQUEUED = "enqueued" - BUILDING = "building" - COMPLETED = "completed" - FAILED = "failed" - CANCELED = "canceled" - - """ - :ivar account_sid: The unique ID of the Account that created this Model Build. - :ivar date_created: The date that this resource was created - :ivar date_updated: The date that this resource was last updated - :ivar assistant_sid: The unique ID of the parent Assistant. - :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar status: - :ivar unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :ivar url: - :ivar build_duration: The time in seconds it took to build the model. - :ivar error_code: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.status: Optional["ModelBuildInstance.Status"] = payload.get("status") - self.unique_name: Optional[str] = payload.get("unique_name") - self.url: Optional[str] = payload.get("url") - self.build_duration: Optional[int] = deserialize.integer( - payload.get("build_duration") - ) - self.error_code: Optional[int] = deserialize.integer(payload.get("error_code")) - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[ModelBuildContext] = None - - @property - def _proxy(self) -> "ModelBuildContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: ModelBuildContext for this ModelBuildInstance - """ - if self._context is None: - self._context = ModelBuildContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the ModelBuildInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ModelBuildInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "ModelBuildInstance": - """ - Fetch the ModelBuildInstance - - - :returns: The fetched ModelBuildInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "ModelBuildInstance": - """ - Asynchronous coroutine to fetch the ModelBuildInstance - - - :returns: The fetched ModelBuildInstance - """ - return await self._proxy.fetch_async() - - def update( - self, unique_name: Union[str, object] = values.unset - ) -> "ModelBuildInstance": - """ - Update the ModelBuildInstance - - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. For example: v0.1 - - :returns: The updated ModelBuildInstance - """ - return self._proxy.update( - unique_name=unique_name, - ) - - async def update_async( - self, unique_name: Union[str, object] = values.unset - ) -> "ModelBuildInstance": - """ - Asynchronous coroutine to update the ModelBuildInstance - - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. For example: v0.1 - - :returns: The updated ModelBuildInstance - """ - return await self._proxy.update_async( - unique_name=unique_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 "".format(context) - - -class ModelBuildContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the ModelBuildContext - - :param version: Version that contains the resource - :param assistant_sid: - :param sid: - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/ModelBuilds/{sid}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the ModelBuildInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ModelBuildInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> ModelBuildInstance: - """ - Fetch the ModelBuildInstance - - - :returns: The fetched ModelBuildInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> ModelBuildInstance: - """ - Asynchronous coroutine to fetch the ModelBuildInstance - - - :returns: The fetched ModelBuildInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - def update( - self, unique_name: Union[str, object] = values.unset - ) -> ModelBuildInstance: - """ - Update the ModelBuildInstance - - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. For example: v0.1 - - :returns: The updated ModelBuildInstance - """ - data = values.of( - { - "UniqueName": unique_name, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, unique_name: Union[str, object] = values.unset - ) -> ModelBuildInstance: - """ - Asynchronous coroutine to update the ModelBuildInstance - - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. For example: v0.1 - - :returns: The updated ModelBuildInstance - """ - data = values.of( - { - "UniqueName": unique_name, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ModelBuildInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_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 "".format(context) - - -class ModelBuildPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> ModelBuildInstance: - """ - Build an instance of ModelBuildInstance - - :param payload: Payload response from the API - """ - return ModelBuildInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class ModelBuildList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the ModelBuildList - - :param version: Version that contains the resource - :param assistant_sid: - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/ModelBuilds".format(**self._solution) - - def create( - self, - status_callback: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> ModelBuildInstance: - """ - Create the ModelBuildInstance - - :param status_callback: - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. For example: v0.1 - - :returns: The created ModelBuildInstance - """ - data = values.of( - { - "StatusCallback": status_callback, - "UniqueName": unique_name, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return ModelBuildInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def create_async( - self, - status_callback: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - ) -> ModelBuildInstance: - """ - Asynchronously create the ModelBuildInstance - - :param status_callback: - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. For example: v0.1 - - :returns: The created ModelBuildInstance - """ - data = values.of( - { - "StatusCallback": status_callback, - "UniqueName": unique_name, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ModelBuildInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[ModelBuildInstance]: - """ - Streams ModelBuildInstance 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[ModelBuildInstance]: - """ - Asynchronously streams ModelBuildInstance 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[ModelBuildInstance]: - """ - Lists ModelBuildInstance 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[ModelBuildInstance]: - """ - Asynchronously lists ModelBuildInstance 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, - ) -> ModelBuildPage: - """ - Retrieve a single page of ModelBuildInstance 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 ModelBuildInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return ModelBuildPage(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, - ) -> ModelBuildPage: - """ - Asynchronously retrieve a single page of ModelBuildInstance 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 ModelBuildInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return ModelBuildPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> ModelBuildPage: - """ - Retrieve a specific page of ModelBuildInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ModelBuildInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return ModelBuildPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> ModelBuildPage: - """ - Asynchronously retrieve a specific page of ModelBuildInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of ModelBuildInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return ModelBuildPage(self._version, response, self._solution) - - def get(self, sid: str) -> ModelBuildContext: - """ - Constructs a ModelBuildContext - - :param sid: - """ - return ModelBuildContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> ModelBuildContext: - """ - Constructs a ModelBuildContext - - :param sid: - """ - return ModelBuildContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/query.py b/twilio/rest/preview/understand/assistant/query.py deleted file mode 100644 index 62fb2e3e11..0000000000 --- a/twilio/rest/preview/understand/assistant/query.py +++ /dev/null @@ -1,715 +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 - - -class QueryInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Query. - :ivar date_created: The date that this resource was created - :ivar date_updated: The date that this resource was last updated - :ivar results: The natural language analysis results which include the Task recognized, the confidence score and a list of identified Fields. - :ivar language: An ISO language-country string of the sample. - :ivar model_build_sid: The unique ID of the Model Build queried. - :ivar query: The end-user's natural language input. - :ivar sample_sid: An optional reference to the Sample created from this query. - :ivar assistant_sid: The unique ID of the parent Assistant. - :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :ivar url: - :ivar source_channel: The communication channel where this end-user input came from - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.results: Optional[Dict[str, object]] = payload.get("results") - self.language: Optional[str] = payload.get("language") - self.model_build_sid: Optional[str] = payload.get("model_build_sid") - self.query: Optional[str] = payload.get("query") - self.sample_sid: Optional[str] = payload.get("sample_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.status: Optional[str] = payload.get("status") - self.url: Optional[str] = payload.get("url") - self.source_channel: Optional[str] = payload.get("source_channel") - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[QueryContext] = None - - @property - def _proxy(self) -> "QueryContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: QueryContext for this QueryInstance - """ - if self._context is None: - self._context = QueryContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the QueryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the QueryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "QueryInstance": - """ - Fetch the QueryInstance - - - :returns: The fetched QueryInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "QueryInstance": - """ - Asynchronous coroutine to fetch the QueryInstance - - - :returns: The fetched QueryInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - sample_sid: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - ) -> "QueryInstance": - """ - Update the QueryInstance - - :param sample_sid: An optional reference to the Sample created from this query. - :param status: A string that described the query status. The values can be: pending_review, reviewed, discarded - - :returns: The updated QueryInstance - """ - return self._proxy.update( - sample_sid=sample_sid, - status=status, - ) - - async def update_async( - self, - sample_sid: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - ) -> "QueryInstance": - """ - Asynchronous coroutine to update the QueryInstance - - :param sample_sid: An optional reference to the Sample created from this query. - :param status: A string that described the query status. The values can be: pending_review, reviewed, discarded - - :returns: The updated QueryInstance - """ - return await self._proxy.update_async( - sample_sid=sample_sid, - status=status, - ) - - 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 QueryContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the QueryContext - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param sid: A 34 character string that uniquely identifies this resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Queries/{sid}".format(**self._solution) - - def delete(self) -> bool: - """ - Deletes the QueryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the QueryInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> QueryInstance: - """ - Fetch the QueryInstance - - - :returns: The fetched QueryInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> QueryInstance: - """ - Asynchronous coroutine to fetch the QueryInstance - - - :returns: The fetched QueryInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - sample_sid: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - ) -> QueryInstance: - """ - Update the QueryInstance - - :param sample_sid: An optional reference to the Sample created from this query. - :param status: A string that described the query status. The values can be: pending_review, reviewed, discarded - - :returns: The updated QueryInstance - """ - data = values.of( - { - "SampleSid": sample_sid, - "Status": status, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - sample_sid: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - ) -> QueryInstance: - """ - Asynchronous coroutine to update the QueryInstance - - :param sample_sid: An optional reference to the Sample created from this query. - :param status: A string that described the query status. The values can be: pending_review, reviewed, discarded - - :returns: The updated QueryInstance - """ - data = values.of( - { - "SampleSid": sample_sid, - "Status": status, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return QueryInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_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 "".format(context) - - -class QueryPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> QueryInstance: - """ - Build an instance of QueryInstance - - :param payload: Payload response from the API - """ - return QueryInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class QueryList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the QueryList - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/Queries".format(**self._solution) - - def create( - self, - language: str, - query: str, - tasks: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - field: Union[str, object] = values.unset, - ) -> QueryInstance: - """ - Create the QueryInstance - - :param language: An ISO language-country string of the sample. - :param query: A user-provided string that uniquely identifies this resource as an alternative to the sid. It can be up to 2048 characters long. - :param tasks: Constraints the query to a set of tasks. Useful when you need to constrain the paths the user can take. Tasks should be comma separated *task-unique-name-1*, *task-unique-name-2* - :param model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param field: Constraints the query to a given Field with an task. Useful when you know the Field you are expecting. It accepts one field in the format *task-unique-name-1*:*field-unique-name* - - :returns: The created QueryInstance - """ - data = values.of( - { - "Language": language, - "Query": query, - "Tasks": tasks, - "ModelBuild": model_build, - "Field": field, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return QueryInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def create_async( - self, - language: str, - query: str, - tasks: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - field: Union[str, object] = values.unset, - ) -> QueryInstance: - """ - Asynchronously create the QueryInstance - - :param language: An ISO language-country string of the sample. - :param query: A user-provided string that uniquely identifies this resource as an alternative to the sid. It can be up to 2048 characters long. - :param tasks: Constraints the query to a set of tasks. Useful when you need to constrain the paths the user can take. Tasks should be comma separated *task-unique-name-1*, *task-unique-name-2* - :param model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param field: Constraints the query to a given Field with an task. Useful when you know the Field you are expecting. It accepts one field in the format *task-unique-name-1*:*field-unique-name* - - :returns: The created QueryInstance - """ - data = values.of( - { - "Language": language, - "Query": query, - "Tasks": tasks, - "ModelBuild": model_build, - "Field": field, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return QueryInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def stream( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[QueryInstance]: - """ - Streams QueryInstance 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 language: An ISO language-country string of the sample. - :param str model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param str status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - model_build=model_build, - status=status, - page_size=limits["page_size"], - ) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[QueryInstance]: - """ - Asynchronously streams QueryInstance 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 language: An ISO language-country string of the sample. - :param str model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param str status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - model_build=model_build, - status=status, - page_size=limits["page_size"], - ) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[QueryInstance]: - """ - Lists QueryInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: An ISO language-country string of the sample. - :param str model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param str status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - model_build=model_build, - status=status, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, object] = values.unset, - status: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[QueryInstance]: - """ - Asynchronously lists QueryInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: An ISO language-country string of the sample. - :param str model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param str status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - model_build=model_build, - status=status, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, 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, - ) -> QueryPage: - """ - Retrieve a single page of QueryInstance records from the API. - Request is executed immediately - - :param language: An ISO language-country string of the sample. - :param model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :param page_token: PageToken provided by the API - :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 QueryInstance - """ - data = values.of( - { - "Language": language, - "ModelBuild": model_build, - "Status": status, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return QueryPage(self._version, response, self._solution) - - async def page_async( - self, - language: Union[str, object] = values.unset, - model_build: Union[str, 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, - ) -> QueryPage: - """ - Asynchronously retrieve a single page of QueryInstance records from the API. - Request is executed immediately - - :param language: An ISO language-country string of the sample. - :param model_build: The Model Build Sid or unique name of the Model Build to be queried. - :param status: A string that described the query status. The values can be: pending_review, reviewed, discarded - :param page_token: PageToken provided by the API - :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 QueryInstance - """ - data = values.of( - { - "Language": language, - "ModelBuild": model_build, - "Status": status, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return QueryPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> QueryPage: - """ - Retrieve a specific page of QueryInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of QueryInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return QueryPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> QueryPage: - """ - Asynchronously retrieve a specific page of QueryInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of QueryInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return QueryPage(self._version, response, self._solution) - - def get(self, sid: str) -> QueryContext: - """ - Constructs a QueryContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return QueryContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> QueryContext: - """ - Constructs a QueryContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return QueryContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/style_sheet.py b/twilio/rest/preview/understand/assistant/style_sheet.py deleted file mode 100644 index 4571fc4cb1..0000000000 --- a/twilio/rest/preview/understand/assistant/style_sheet.py +++ /dev/null @@ -1,273 +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, Optional, Union -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 - - -class StyleSheetInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Assistant - :ivar assistant_sid: The unique ID of the Assistant - :ivar url: - :ivar data: The JSON style sheet object - """ - - def __init__(self, version: Version, payload: Dict[str, Any], assistant_sid: str): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.url: Optional[str] = payload.get("url") - self.data: Optional[Dict[str, object]] = payload.get("data") - - self._solution = { - "assistant_sid": assistant_sid, - } - self._context: Optional[StyleSheetContext] = None - - @property - def _proxy(self) -> "StyleSheetContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: StyleSheetContext for this StyleSheetInstance - """ - if self._context is None: - self._context = StyleSheetContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - ) - return self._context - - def fetch(self) -> "StyleSheetInstance": - """ - Fetch the StyleSheetInstance - - - :returns: The fetched StyleSheetInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "StyleSheetInstance": - """ - Asynchronous coroutine to fetch the StyleSheetInstance - - - :returns: The fetched StyleSheetInstance - """ - return await self._proxy.fetch_async() - - def update( - self, style_sheet: Union[object, object] = values.unset - ) -> "StyleSheetInstance": - """ - Update the StyleSheetInstance - - :param style_sheet: The JSON Style sheet string - - :returns: The updated StyleSheetInstance - """ - return self._proxy.update( - style_sheet=style_sheet, - ) - - async def update_async( - self, style_sheet: Union[object, object] = values.unset - ) -> "StyleSheetInstance": - """ - Asynchronous coroutine to update the StyleSheetInstance - - :param style_sheet: The JSON Style sheet string - - :returns: The updated StyleSheetInstance - """ - return await self._proxy.update_async( - style_sheet=style_sheet, - ) - - 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 StyleSheetContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the StyleSheetContext - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/StyleSheet".format(**self._solution) - - def fetch(self) -> StyleSheetInstance: - """ - Fetch the StyleSheetInstance - - - :returns: The fetched StyleSheetInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return StyleSheetInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - async def fetch_async(self) -> StyleSheetInstance: - """ - Asynchronous coroutine to fetch the StyleSheetInstance - - - :returns: The fetched StyleSheetInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return StyleSheetInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - ) - - def update( - self, style_sheet: Union[object, object] = values.unset - ) -> StyleSheetInstance: - """ - Update the StyleSheetInstance - - :param style_sheet: The JSON Style sheet string - - :returns: The updated StyleSheetInstance - """ - data = values.of( - { - "StyleSheet": serialize.object(style_sheet), - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return StyleSheetInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def update_async( - self, style_sheet: Union[object, object] = values.unset - ) -> StyleSheetInstance: - """ - Asynchronous coroutine to update the StyleSheetInstance - - :param style_sheet: The JSON Style sheet string - - :returns: The updated StyleSheetInstance - """ - data = values.of( - { - "StyleSheet": serialize.object(style_sheet), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return StyleSheetInstance( - self._version, payload, assistant_sid=self._solution["assistant_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 StyleSheetList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the StyleSheetList - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - - def get(self) -> StyleSheetContext: - """ - Constructs a StyleSheetContext - - """ - return StyleSheetContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __call__(self) -> StyleSheetContext: - """ - Constructs a StyleSheetContext - - """ - return StyleSheetContext( - self._version, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/task/__init__.py b/twilio/rest/preview/understand/assistant/task/__init__.py deleted file mode 100644 index 135a421ec6..0000000000 --- a/twilio/rest/preview/understand/assistant/task/__init__.py +++ /dev/null @@ -1,760 +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.understand.assistant.task.field import FieldList -from twilio.rest.preview.understand.assistant.task.sample import SampleList -from twilio.rest.preview.understand.assistant.task.task_actions import TaskActionsList -from twilio.rest.preview.understand.assistant.task.task_statistics import ( - TaskStatisticsList, -) - - -class TaskInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Task. - :ivar date_created: The date that this resource was created - :ivar date_updated: The date that this resource was last updated - :ivar friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :ivar links: - :ivar assistant_sid: The unique ID of the Assistant. - :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :ivar actions_url: User-provided HTTP endpoint where from the assistant fetches actions - :ivar url: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.friendly_name: Optional[str] = payload.get("friendly_name") - self.links: Optional[Dict[str, object]] = payload.get("links") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.actions_url: Optional[str] = payload.get("actions_url") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid or self.sid, - } - self._context: Optional[TaskContext] = None - - @property - def _proxy(self) -> "TaskContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: TaskContext for this TaskInstance - """ - if self._context is None: - self._context = TaskContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the TaskInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the TaskInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "TaskInstance": - """ - Fetch the TaskInstance - - - :returns: The fetched TaskInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "TaskInstance": - """ - Asynchronous coroutine to fetch the TaskInstance - - - :returns: The fetched TaskInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> "TaskInstance": - """ - Update the TaskInstance - - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param actions: A user-provided JSON object encoded as a string to specify the actions for this task. It is optional and non-unique. - :param actions_url: User-provided HTTP endpoint where from the assistant fetches actions - - :returns: The updated TaskInstance - """ - return self._proxy.update( - friendly_name=friendly_name, - unique_name=unique_name, - actions=actions, - actions_url=actions_url, - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> "TaskInstance": - """ - Asynchronous coroutine to update the TaskInstance - - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param actions: A user-provided JSON object encoded as a string to specify the actions for this task. It is optional and non-unique. - :param actions_url: User-provided HTTP endpoint where from the assistant fetches actions - - :returns: The updated TaskInstance - """ - return await self._proxy.update_async( - friendly_name=friendly_name, - unique_name=unique_name, - actions=actions, - actions_url=actions_url, - ) - - @property - def fields(self) -> FieldList: - """ - Access the fields - """ - return self._proxy.fields - - @property - def samples(self) -> SampleList: - """ - Access the samples - """ - return self._proxy.samples - - @property - def task_actions(self) -> TaskActionsList: - """ - Access the task_actions - """ - return self._proxy.task_actions - - @property - def statistics(self) -> TaskStatisticsList: - """ - Access the statistics - """ - return self._proxy.statistics - - 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 TaskContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, sid: str): - """ - Initialize the TaskContext - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - :param sid: A 34 character string that uniquely identifies this resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{sid}".format(**self._solution) - - self._fields: Optional[FieldList] = None - self._samples: Optional[SampleList] = None - self._task_actions: Optional[TaskActionsList] = None - self._statistics: Optional[TaskStatisticsList] = None - - def delete(self) -> bool: - """ - Deletes the TaskInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the TaskInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> TaskInstance: - """ - Fetch the TaskInstance - - - :returns: The fetched TaskInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> TaskInstance: - """ - Asynchronous coroutine to fetch the TaskInstance - - - :returns: The fetched TaskInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> TaskInstance: - """ - Update the TaskInstance - - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param actions: A user-provided JSON object encoded as a string to specify the actions for this task. It is optional and non-unique. - :param actions_url: User-provided HTTP endpoint where from the assistant fetches actions - - :returns: The updated TaskInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Actions": serialize.object(actions), - "ActionsUrl": actions_url, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - friendly_name: Union[str, object] = values.unset, - unique_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> TaskInstance: - """ - Asynchronous coroutine to update the TaskInstance - - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param actions: A user-provided JSON object encoded as a string to specify the actions for this task. It is optional and non-unique. - :param actions_url: User-provided HTTP endpoint where from the assistant fetches actions - - :returns: The updated TaskInstance - """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "Actions": serialize.object(actions), - "ActionsUrl": actions_url, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - sid=self._solution["sid"], - ) - - @property - def fields(self) -> FieldList: - """ - Access the fields - """ - if self._fields is None: - self._fields = FieldList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._fields - - @property - def samples(self) -> SampleList: - """ - Access the samples - """ - if self._samples is None: - self._samples = SampleList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._samples - - @property - def task_actions(self) -> TaskActionsList: - """ - Access the task_actions - """ - if self._task_actions is None: - self._task_actions = TaskActionsList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._task_actions - - @property - def statistics(self) -> TaskStatisticsList: - """ - Access the statistics - """ - if self._statistics is None: - self._statistics = TaskStatisticsList( - self._version, - self._solution["assistant_sid"], - self._solution["sid"], - ) - return self._statistics - - 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 TaskPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> TaskInstance: - """ - Build an instance of TaskInstance - - :param payload: Payload response from the API - """ - return TaskInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class TaskList(ListResource): - def __init__(self, version: Version, assistant_sid: str): - """ - Initialize the TaskList - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks".format(**self._solution) - - def create( - self, - unique_name: str, - friendly_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> TaskInstance: - """ - Create the TaskInstance - - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param actions: A user-provided JSON object encoded as a string to specify the actions for this task. It is optional and non-unique. - :param actions_url: User-provided HTTP endpoint where from the assistant fetches actions - - :returns: The created TaskInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - "Actions": serialize.object(actions), - "ActionsUrl": actions_url, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - async def create_async( - self, - unique_name: str, - friendly_name: Union[str, object] = values.unset, - actions: Union[object, object] = values.unset, - actions_url: Union[str, object] = values.unset, - ) -> TaskInstance: - """ - Asynchronously create the TaskInstance - - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :param friendly_name: A user-provided string that identifies this resource. It is non-unique and can up to 255 characters long. - :param actions: A user-provided JSON object encoded as a string to specify the actions for this task. It is optional and non-unique. - :param actions_url: User-provided HTTP endpoint where from the assistant fetches actions - - :returns: The created TaskInstance - """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - "Actions": serialize.object(actions), - "ActionsUrl": actions_url, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskInstance( - self._version, payload, assistant_sid=self._solution["assistant_sid"] - ) - - def stream( - self, - 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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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[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 limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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[TaskInstance]: - """ - Lists TaskInstance 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[TaskInstance]: - """ - Asynchronously lists TaskInstance 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, - ) -> TaskPage: - """ - Retrieve a single page of TaskInstance 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 TaskInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return TaskPage(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, - ) -> TaskPage: - """ - Asynchronously retrieve a single page of TaskInstance 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 TaskInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return TaskPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> TaskPage: - """ - Retrieve a specific page of TaskInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of TaskInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return TaskPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> TaskPage: - """ - Asynchronously retrieve a specific page of TaskInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of TaskInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return TaskPage(self._version, response, self._solution) - - def get(self, sid: str) -> TaskContext: - """ - Constructs a TaskContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return TaskContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __call__(self, sid: str) -> TaskContext: - """ - Constructs a TaskContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return TaskContext( - self._version, assistant_sid=self._solution["assistant_sid"], sid=sid - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/task/field.py b/twilio/rest/preview/understand/assistant/task/field.py deleted file mode 100644 index e8f4aa3a8c..0000000000 --- a/twilio/rest/preview/understand/assistant/task/field.py +++ /dev/null @@ -1,549 +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 - - -class FieldInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Field. - :ivar date_created: The date that this resource was created - :ivar date_updated: The date that this resource was last updated - :ivar field_type: The Field Type of this field. It can be any [Built-in Field Type](https://www.twilio.com/docs/assistant/api/built-in-field-types) or the unique_name or sid of a custom Field Type. - :ivar task_sid: The unique ID of the Task associated with this Field. - :ivar assistant_sid: The unique ID of the parent Assistant. - :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - :ivar url: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - task_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.field_type: Optional[str] = payload.get("field_type") - self.task_sid: Optional[str] = payload.get("task_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.unique_name: Optional[str] = payload.get("unique_name") - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - "sid": sid or self.sid, - } - self._context: Optional[FieldContext] = None - - @property - def _proxy(self) -> "FieldContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: FieldContext for this FieldInstance - """ - if self._context is None: - self._context = FieldContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the FieldInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "FieldInstance": - """ - Fetch the FieldInstance - - - :returns: The fetched FieldInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "FieldInstance": - """ - Asynchronous coroutine to fetch the FieldInstance - - - :returns: The fetched FieldInstance - """ - 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 "".format(context) - - -class FieldContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, task_sid: str, sid: str): - """ - Initialize the FieldContext - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - :param sid: A 34 character string that uniquely identifies this resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Fields/{sid}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the FieldInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the FieldInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> FieldInstance: - """ - Fetch the FieldInstance - - - :returns: The fetched FieldInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> FieldInstance: - """ - Asynchronous coroutine to fetch the FieldInstance - - - :returns: The fetched FieldInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_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 "".format(context) - - -class FieldPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> FieldInstance: - """ - Build an instance of FieldInstance - - :param payload: Payload response from the API - """ - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class FieldList(ListResource): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the FieldList - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Fields".format( - **self._solution - ) - - def create(self, field_type: str, unique_name: str) -> FieldInstance: - """ - Create the FieldInstance - - :param field_type: The unique name or sid of the FieldType. It can be any [Built-in Field Type](https://www.twilio.com/docs/assistant/api/built-in-field-types) or the unique_name or the Field Type sid of a custom Field Type. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - - :returns: The created FieldInstance - """ - data = values.of( - { - "FieldType": field_type, - "UniqueName": unique_name, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def create_async(self, field_type: str, unique_name: str) -> FieldInstance: - """ - Asynchronously create the FieldInstance - - :param field_type: The unique name or sid of the FieldType. It can be any [Built-in Field Type](https://www.twilio.com/docs/assistant/api/built-in-field-types) or the unique_name or the Field Type sid of a custom Field Type. - :param unique_name: A user-provided string that uniquely identifies this resource as an alternative to the sid. Unique up to 64 characters long. - - :returns: The created FieldInstance - """ - data = values.of( - { - "FieldType": field_type, - "UniqueName": unique_name, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return FieldInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def stream( - self, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[FieldInstance]: - """ - Streams FieldInstance 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[FieldInstance]: - """ - Asynchronously streams FieldInstance 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[FieldInstance]: - """ - Lists FieldInstance 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[FieldInstance]: - """ - Asynchronously lists FieldInstance 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, - ) -> FieldPage: - """ - Retrieve a single page of FieldInstance 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 FieldInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return FieldPage(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, - ) -> FieldPage: - """ - Asynchronously retrieve a single page of FieldInstance 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 FieldInstance - """ - data = values.of( - { - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return FieldPage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> FieldPage: - """ - Retrieve a specific page of FieldInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return FieldPage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> FieldPage: - """ - Asynchronously retrieve a specific page of FieldInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of FieldInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return FieldPage(self._version, response, self._solution) - - def get(self, sid: str) -> FieldContext: - """ - Constructs a FieldContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return FieldContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=sid, - ) - - def __call__(self, sid: str) -> FieldContext: - """ - Constructs a FieldContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return FieldContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=sid, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/task/sample.py b/twilio/rest/preview/understand/assistant/task/sample.py deleted file mode 100644 index ef8719c6ac..0000000000 --- a/twilio/rest/preview/understand/assistant/task/sample.py +++ /dev/null @@ -1,697 +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 - - -class SampleInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Sample. - :ivar date_created: The date that this resource was created - :ivar date_updated: The date that this resource was last updated - :ivar task_sid: The unique ID of the Task associated with this Sample. - :ivar language: An ISO language-country string of the sample. - :ivar assistant_sid: The unique ID of the Assistant. - :ivar sid: A 34 character string that uniquely identifies this resource. - :ivar tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :ivar url: - :ivar source_channel: The communication channel the sample was captured. It can be: *voice*, *sms*, *chat*, *alexa*, *google-assistant*, or *slack*. If not included the value will be null - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - task_sid: str, - sid: Optional[str] = None, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_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.task_sid: Optional[str] = payload.get("task_sid") - self.language: Optional[str] = payload.get("language") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.sid: Optional[str] = payload.get("sid") - self.tagged_text: Optional[str] = payload.get("tagged_text") - self.url: Optional[str] = payload.get("url") - self.source_channel: Optional[str] = payload.get("source_channel") - - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - "sid": sid or self.sid, - } - self._context: Optional[SampleContext] = None - - @property - def _proxy(self) -> "SampleContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: SampleContext for this SampleInstance - """ - if self._context is None: - self._context = SampleContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - return self._context - - def delete(self) -> bool: - """ - Deletes the SampleInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._proxy.delete() - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SampleInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._proxy.delete_async() - - def fetch(self) -> "SampleInstance": - """ - Fetch the SampleInstance - - - :returns: The fetched SampleInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "SampleInstance": - """ - Asynchronous coroutine to fetch the SampleInstance - - - :returns: The fetched SampleInstance - """ - return await self._proxy.fetch_async() - - def update( - self, - language: Union[str, object] = values.unset, - tagged_text: Union[str, object] = values.unset, - source_channel: Union[str, object] = values.unset, - ) -> "SampleInstance": - """ - Update the SampleInstance - - :param language: An ISO language-country string of the sample. - :param tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :param source_channel: The communication channel the sample was captured. It can be: *voice*, *sms*, *chat*, *alexa*, *google-assistant*, or *slack*. If not included the value will be null - - :returns: The updated SampleInstance - """ - return self._proxy.update( - language=language, - tagged_text=tagged_text, - source_channel=source_channel, - ) - - async def update_async( - self, - language: Union[str, object] = values.unset, - tagged_text: Union[str, object] = values.unset, - source_channel: Union[str, object] = values.unset, - ) -> "SampleInstance": - """ - Asynchronous coroutine to update the SampleInstance - - :param language: An ISO language-country string of the sample. - :param tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :param source_channel: The communication channel the sample was captured. It can be: *voice*, *sms*, *chat*, *alexa*, *google-assistant*, or *slack*. If not included the value will be null - - :returns: The updated SampleInstance - """ - return await self._proxy.update_async( - language=language, - tagged_text=tagged_text, - source_channel=source_channel, - ) - - 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 SampleContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, task_sid: str, sid: str): - """ - Initialize the SampleContext - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - :param task_sid: The unique ID of the Task associated with this Sample. - :param sid: A 34 character string that uniquely identifies this resource. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - "sid": sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples/{sid}".format( - **self._solution - ) - - def delete(self) -> bool: - """ - Deletes the SampleInstance - - - :returns: True if delete succeeds, False otherwise - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the SampleInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> SampleInstance: - """ - Fetch the SampleInstance - - - :returns: The fetched SampleInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - async def fetch_async(self) -> SampleInstance: - """ - Asynchronous coroutine to fetch the SampleInstance - - - :returns: The fetched SampleInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - def update( - self, - language: Union[str, object] = values.unset, - tagged_text: Union[str, object] = values.unset, - source_channel: Union[str, object] = values.unset, - ) -> SampleInstance: - """ - Update the SampleInstance - - :param language: An ISO language-country string of the sample. - :param tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :param source_channel: The communication channel the sample was captured. It can be: *voice*, *sms*, *chat*, *alexa*, *google-assistant*, or *slack*. If not included the value will be null - - :returns: The updated SampleInstance - """ - data = values.of( - { - "Language": language, - "TaggedText": tagged_text, - "SourceChannel": source_channel, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=self._solution["sid"], - ) - - async def update_async( - self, - language: Union[str, object] = values.unset, - tagged_text: Union[str, object] = values.unset, - source_channel: Union[str, object] = values.unset, - ) -> SampleInstance: - """ - Asynchronous coroutine to update the SampleInstance - - :param language: An ISO language-country string of the sample. - :param tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :param source_channel: The communication channel the sample was captured. It can be: *voice*, *sms*, *chat*, *alexa*, *google-assistant*, or *slack*. If not included the value will be null - - :returns: The updated SampleInstance - """ - data = values.of( - { - "Language": language, - "TaggedText": tagged_text, - "SourceChannel": source_channel, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_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 "".format(context) - - -class SamplePage(Page): - def get_instance(self, payload: Dict[str, Any]) -> SampleInstance: - """ - Build an instance of SampleInstance - - :param payload: Payload response from the API - """ - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class SampleList(ListResource): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the SampleList - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the Assistant. - :param task_sid: The unique ID of the Task associated with this Sample. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Samples".format( - **self._solution - ) - - def create( - self, - language: str, - tagged_text: str, - source_channel: Union[str, object] = values.unset, - ) -> SampleInstance: - """ - Create the SampleInstance - - :param language: An ISO language-country string of the sample. - :param tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :param source_channel: The communication channel the sample was captured. It can be: *voice*, *sms*, *chat*, *alexa*, *google-assistant*, or *slack*. If not included the value will be null - - :returns: The created SampleInstance - """ - data = values.of( - { - "Language": language, - "TaggedText": tagged_text, - "SourceChannel": source_channel, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def create_async( - self, - language: str, - tagged_text: str, - source_channel: Union[str, object] = values.unset, - ) -> SampleInstance: - """ - Asynchronously create the SampleInstance - - :param language: An ISO language-country string of the sample. - :param tagged_text: The text example of how end-users may express this task. The sample may contain Field tag blocks. - :param source_channel: The communication channel the sample was captured. It can be: *voice*, *sms*, *chat*, *alexa*, *google-assistant*, or *slack*. If not included the value will be null - - :returns: The created SampleInstance - """ - data = values.of( - { - "Language": language, - "TaggedText": tagged_text, - "SourceChannel": source_channel, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - return SampleInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def stream( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> Iterator[SampleInstance]: - """ - Streams SampleInstance 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 language: An ISO language-country string of the sample. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(language=language, page_size=limits["page_size"]) - - return self._version.stream(page, limits["limit"]) - - async def stream_async( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> AsyncIterator[SampleInstance]: - """ - Asynchronously streams SampleInstance 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 language: An ISO language-country string of the sample. - :param limit: Upper limit for the number of records to return. stream() - guarantees to never return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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(language=language, page_size=limits["page_size"]) - - return self._version.stream_async(page, limits["limit"]) - - def list( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SampleInstance]: - """ - Lists SampleInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: An ISO language-country string of the sample. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - limit=limit, - page_size=page_size, - ) - ) - - async def list_async( - self, - language: Union[str, object] = values.unset, - limit: Optional[int] = None, - page_size: Optional[int] = None, - ) -> List[SampleInstance]: - """ - Asynchronously lists SampleInstance records from the API as a list. - Unlike stream(), this operation is eager and will load `limit` records into - memory before returning. - - :param str language: An ISO language-country string of the sample. - :param limit: Upper limit for the number of records to return. list() guarantees - never to return more than limit. Default is no limit - :param page_size: Number of records to fetch per request, when not set will use - the default value of 50 records. If no page_size is defined - 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( - language=language, - limit=limit, - page_size=page_size, - ) - ] - - def page( - self, - language: 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, - ) -> SamplePage: - """ - Retrieve a single page of SampleInstance records from the API. - Request is executed immediately - - :param language: An ISO language-country string of the sample. - :param page_token: PageToken provided by the API - :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 SampleInstance - """ - data = values.of( - { - "Language": language, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - return SamplePage(self._version, response, self._solution) - - async def page_async( - self, - language: 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, - ) -> SamplePage: - """ - Asynchronously retrieve a single page of SampleInstance records from the API. - Request is executed immediately - - :param language: An ISO language-country string of the sample. - :param page_token: PageToken provided by the API - :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 SampleInstance - """ - data = values.of( - { - "Language": language, - "PageToken": page_token, - "Page": page_number, - "PageSize": page_size, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - return SamplePage(self._version, response, self._solution) - - def get_page(self, target_url: str) -> SamplePage: - """ - Retrieve a specific page of SampleInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SampleInstance - """ - response = self._version.domain.twilio.request("GET", target_url) - return SamplePage(self._version, response, self._solution) - - async def get_page_async(self, target_url: str) -> SamplePage: - """ - Asynchronously retrieve a specific page of SampleInstance records from the API. - Request is executed immediately - - :param target_url: API-generated URL for the requested results page - - :returns: Page of SampleInstance - """ - response = await self._version.domain.twilio.request_async("GET", target_url) - return SamplePage(self._version, response, self._solution) - - def get(self, sid: str) -> SampleContext: - """ - Constructs a SampleContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return SampleContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=sid, - ) - - def __call__(self, sid: str) -> SampleContext: - """ - Constructs a SampleContext - - :param sid: A 34 character string that uniquely identifies this resource. - """ - return SampleContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - sid=sid, - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/task/task_actions.py b/twilio/rest/preview/understand/assistant/task/task_actions.py deleted file mode 100644 index 41366bbb96..0000000000 --- a/twilio/rest/preview/understand/assistant/task/task_actions.py +++ /dev/null @@ -1,301 +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, Optional, Union -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 - - -class TaskActionsInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Field. - :ivar assistant_sid: The unique ID of the parent Assistant. - :ivar task_sid: The unique ID of the Task. - :ivar url: - :ivar data: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - task_sid: str, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.task_sid: Optional[str] = payload.get("task_sid") - self.url: Optional[str] = payload.get("url") - self.data: Optional[Dict[str, object]] = payload.get("data") - - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._context: Optional[TaskActionsContext] = None - - @property - def _proxy(self) -> "TaskActionsContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: TaskActionsContext for this TaskActionsInstance - """ - if self._context is None: - self._context = TaskActionsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - return self._context - - def fetch(self) -> "TaskActionsInstance": - """ - Fetch the TaskActionsInstance - - - :returns: The fetched TaskActionsInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "TaskActionsInstance": - """ - Asynchronous coroutine to fetch the TaskActionsInstance - - - :returns: The fetched TaskActionsInstance - """ - return await self._proxy.fetch_async() - - def update( - self, actions: Union[object, object] = values.unset - ) -> "TaskActionsInstance": - """ - Update the TaskActionsInstance - - :param actions: The JSON actions that instruct the Assistant how to perform this task. - - :returns: The updated TaskActionsInstance - """ - return self._proxy.update( - actions=actions, - ) - - async def update_async( - self, actions: Union[object, object] = values.unset - ) -> "TaskActionsInstance": - """ - Asynchronous coroutine to update the TaskActionsInstance - - :param actions: The JSON actions that instruct the Assistant how to perform this task. - - :returns: The updated TaskActionsInstance - """ - return await self._proxy.update_async( - actions=actions, - ) - - 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 TaskActionsContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the TaskActionsContext - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Actions".format( - **self._solution - ) - - def fetch(self) -> TaskActionsInstance: - """ - Fetch the TaskActionsInstance - - - :returns: The fetched TaskActionsInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def fetch_async(self) -> TaskActionsInstance: - """ - Asynchronous coroutine to fetch the TaskActionsInstance - - - :returns: The fetched TaskActionsInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def update( - self, actions: Union[object, object] = values.unset - ) -> TaskActionsInstance: - """ - Update the TaskActionsInstance - - :param actions: The JSON actions that instruct the Assistant how to perform this task. - - :returns: The updated TaskActionsInstance - """ - data = values.of( - { - "Actions": serialize.object(actions), - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def update_async( - self, actions: Union[object, object] = values.unset - ) -> TaskActionsInstance: - """ - Asynchronous coroutine to update the TaskActionsInstance - - :param actions: The JSON actions that instruct the Assistant how to perform this task. - - :returns: The updated TaskActionsInstance - """ - data = values.of( - { - "Actions": serialize.object(actions), - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return TaskActionsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_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 TaskActionsList(ListResource): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the TaskActionsList - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - - def get(self) -> TaskActionsContext: - """ - Constructs a TaskActionsContext - - """ - return TaskActionsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __call__(self) -> TaskActionsContext: - """ - Constructs a TaskActionsContext - - """ - return TaskActionsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/understand/assistant/task/task_statistics.py b/twilio/rest/preview/understand/assistant/task/task_statistics.py deleted file mode 100644 index 07375954c7..0000000000 --- a/twilio/rest/preview/understand/assistant/task/task_statistics.py +++ /dev/null @@ -1,221 +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, Optional -from twilio.base import deserialize -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 TaskStatisticsInstance(InstanceResource): - - """ - :ivar account_sid: The unique ID of the Account that created this Field. - :ivar assistant_sid: The unique ID of the parent Assistant. - :ivar task_sid: The unique ID of the Task associated with this Field. - :ivar samples_count: The total number of Samples associated with this Task. - :ivar fields_count: The total number of Fields associated with this Task. - :ivar url: - """ - - def __init__( - self, - version: Version, - payload: Dict[str, Any], - assistant_sid: str, - task_sid: str, - ): - super().__init__(version) - - self.account_sid: Optional[str] = payload.get("account_sid") - self.assistant_sid: Optional[str] = payload.get("assistant_sid") - self.task_sid: Optional[str] = payload.get("task_sid") - self.samples_count: Optional[int] = deserialize.integer( - payload.get("samples_count") - ) - self.fields_count: Optional[int] = deserialize.integer( - payload.get("fields_count") - ) - self.url: Optional[str] = payload.get("url") - - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._context: Optional[TaskStatisticsContext] = None - - @property - def _proxy(self) -> "TaskStatisticsContext": - """ - Generate an instance context for the instance, the context is capable of - performing various actions. All instance actions are proxied to the context - - :returns: TaskStatisticsContext for this TaskStatisticsInstance - """ - if self._context is None: - self._context = TaskStatisticsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - return self._context - - def fetch(self) -> "TaskStatisticsInstance": - """ - Fetch the TaskStatisticsInstance - - - :returns: The fetched TaskStatisticsInstance - """ - return self._proxy.fetch() - - async def fetch_async(self) -> "TaskStatisticsInstance": - """ - Asynchronous coroutine to fetch the TaskStatisticsInstance - - - :returns: The fetched TaskStatisticsInstance - """ - 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 "".format(context) - - -class TaskStatisticsContext(InstanceContext): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the TaskStatisticsContext - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - self._uri = "/Assistants/{assistant_sid}/Tasks/{task_sid}/Statistics".format( - **self._solution - ) - - def fetch(self) -> TaskStatisticsInstance: - """ - Fetch the TaskStatisticsInstance - - - :returns: The fetched TaskStatisticsInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - return TaskStatisticsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - async def fetch_async(self) -> TaskStatisticsInstance: - """ - Asynchronous coroutine to fetch the TaskStatisticsInstance - - - :returns: The fetched TaskStatisticsInstance - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - return TaskStatisticsInstance( - self._version, - payload, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_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 TaskStatisticsList(ListResource): - def __init__(self, version: Version, assistant_sid: str, task_sid: str): - """ - Initialize the TaskStatisticsList - - :param version: Version that contains the resource - :param assistant_sid: The unique ID of the parent Assistant. - :param task_sid: The unique ID of the Task associated with this Field. - - """ - super().__init__(version) - - # Path Solution - self._solution = { - "assistant_sid": assistant_sid, - "task_sid": task_sid, - } - - def get(self) -> TaskStatisticsContext: - """ - Constructs a TaskStatisticsContext - - """ - return TaskStatisticsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __call__(self) -> TaskStatisticsContext: - """ - Constructs a TaskStatisticsContext - - """ - return TaskStatisticsContext( - self._version, - assistant_sid=self._solution["assistant_sid"], - task_sid=self._solution["task_sid"], - ) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" diff --git a/twilio/rest/preview/wireless/__init__.py b/twilio/rest/preview/wireless/__init__.py index 24f2ea0f0d..85ed4fb54d 100644 --- a/twilio/rest/preview/wireless/__init__.py +++ b/twilio/rest/preview/wireless/__init__.py @@ -21,6 +21,7 @@ class Wireless(Version): + def __init__(self, domain: Domain): """ Initialize the Wireless version of Preview diff --git a/twilio/rest/preview/wireless/command.py b/twilio/rest/preview/wireless/command.py index 4f3e4603af..1ca73b5b3b 100644 --- a/twilio/rest/preview/wireless/command.py +++ b/twilio/rest/preview/wireless/command.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class CommandInstance(InstanceResource): - """ :ivar sid: :ivar account_sid: @@ -63,6 +62,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[CommandContext] = None @property @@ -98,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 @@ -109,6 +127,7 @@ def __repr__(self) -> str: class CommandContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CommandContext @@ -124,6 +143,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Commands/{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) -> CommandInstance: """ Fetch the CommandInstance @@ -131,17 +166,43 @@ def fetch(self) -> CommandInstance: :returns: The fetched CommandInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CommandInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommandInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CommandInstance: """ @@ -150,17 +211,27 @@ async def fetch_async(self) -> CommandInstance: :returns: The fetched CommandInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CommandInstance( + 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: """ @@ -173,12 +244,14 @@ def __repr__(self) -> str: class CommandPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: """ Build an instance of CommandInstance :param payload: Payload response from the API """ + return CommandInstance(self._version, payload) def __repr__(self) -> str: @@ -191,6 +264,7 @@ def __repr__(self) -> str: class CommandList(ListResource): + def __init__(self, version: Version): """ Initialize the CommandList @@ -202,6 +276,44 @@ def __init__(self, version: Version): self._uri = "/Commands" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Command": command, + "Device": device, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_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, command: str, @@ -225,6 +337,69 @@ def create( :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( { "Command": command, @@ -236,14 +411,15 @@ def create( "IncludeSid": include_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CommandInstance(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, @@ -268,25 +444,51 @@ async def create_async( :returns: The created CommandInstance """ - data = values.of( - { - "Command": command, - "Device": device, - "Sim": sim, - "CallbackMethod": callback_method, - "CallbackUrl": callback_url, - "CommandMode": command_mode, - "IncludeSid": include_sid, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CommandInstance(self._version, payload) + :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, @@ -366,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, @@ -393,6 +671,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( device=device, @@ -431,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( @@ -443,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, @@ -479,7 +833,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CommandPage(self._version, response) async def page_async( @@ -518,11 +878,109 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 04b16f5b38..46a4445e4d 100644 --- a/twilio/rest/preview/wireless/rate_plan.py +++ b/twilio/rest/preview/wireless/rate_plan.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class RatePlanInstance(InstanceResource): - """ :ivar sid: :ivar unique_name: @@ -73,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RatePlanContext] = None @property @@ -108,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 @@ -126,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, @@ -162,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 @@ -173,6 +245,7 @@ def __repr__(self) -> str: class RatePlanContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the RatePlanContext @@ -188,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 @@ -195,9 +282,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -207,9 +316,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance 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) -> RatePlanInstance: @@ -219,17 +352,43 @@ def fetch(self) -> RatePlanInstance: :returns: The fetched RatePlanInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RatePlanInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RatePlanInstance: """ @@ -238,17 +397,55 @@ async def fetch_async(self) -> RatePlanInstance: :returns: The fetched RatePlanInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RatePlanInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "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, @@ -263,20 +460,57 @@ def update( :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( { "UniqueName": unique_name, "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -291,20 +525,29 @@ async def update_async( :returns: The updated RatePlanInstance """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - } + payload, _, _ = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -317,12 +560,14 @@ def __repr__(self) -> str: class RatePlanPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: """ Build an instance of RatePlanInstance :param payload: Payload response from the API """ + return RatePlanInstance(self._version, payload) def __repr__(self) -> str: @@ -335,6 +580,7 @@ def __repr__(self) -> str: class RatePlanList(ListResource): + def __init__(self, version: Version): """ Initialize the RatePlanList @@ -346,6 +592,54 @@ def __init__(self, version: Version): self._uri = "/RatePlans" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "DataEnabled": serialize.boolean_to_string(data_enabled), + "DataLimit": data_limit, + "DataMetering": data_metering, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "CommandsEnabled": serialize.boolean_to_string(commands_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), + "InternationalRoaming": serialize.map( + international_roaming, lambda e: 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.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, unique_name: Union[str, object] = values.unset, @@ -375,30 +669,111 @@ def create( :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( { "UniqueName": unique_name, "FriendlyName": friendly_name, - "DataEnabled": data_enabled, + "DataEnabled": serialize.boolean_to_string(data_enabled), "DataLimit": data_limit, "DataMetering": data_metering, - "MessagingEnabled": messaging_enabled, - "VoiceEnabled": voice_enabled, - "CommandsEnabled": commands_enabled, - "NationalRoamingEnabled": national_roaming_enabled, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "CommandsEnabled": serialize.boolean_to_string(commands_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), "InternationalRoaming": serialize.map( international_roaming, lambda e: e ), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RatePlanInstance(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, @@ -429,30 +804,63 @@ async def create_async( :returns: The created RatePlanInstance """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - "DataEnabled": data_enabled, - "DataLimit": data_limit, - "DataMetering": data_metering, - "MessagingEnabled": messaging_enabled, - "VoiceEnabled": voice_enabled, - "CommandsEnabled": commands_enabled, - "NationalRoamingEnabled": national_roaming_enabled, - "InternationalRoaming": serialize.map( - international_roaming, lambda e: e - ), - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return RatePlanInstance(self._version, payload) + :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, @@ -504,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, @@ -523,6 +981,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -549,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( @@ -557,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, @@ -581,7 +1091,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 RatePlanPage(self._version, response) async def page_async( @@ -608,11 +1124,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 3a5dd7e770..ac6b78788d 100644 --- a/twilio/rest/preview/wireless/sim/__init__.py +++ b/twilio/rest/preview/wireless/sim/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class SimInstance(InstanceResource): - """ :ivar sid: :ivar unique_name: @@ -88,6 +87,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SimContext] = None @property @@ -123,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, @@ -243,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: """ @@ -261,6 +399,7 @@ def __repr__(self) -> str: class SimContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SimContext @@ -278,6 +417,22 @@ def __init__(self, version: Version, sid: str): self._usage: Optional[UsageList] = None + 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) -> SimInstance: """ Fetch the SimInstance @@ -285,17 +440,43 @@ def fetch(self) -> SimInstance: :returns: The fetched SimInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SimInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SimInstance: """ @@ -304,19 +485,29 @@ async def fetch_async(self) -> SimInstance: :returns: The fetched SimInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SimInstance( + 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( + def _update( self, unique_name: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, @@ -334,29 +525,14 @@ def update( voice_fallback_url: Union[str, object] = values.unset, voice_method: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, - ) -> SimInstance: + ) -> tuple: """ - Update the SimInstance - - :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: + Internal helper for update operation - :returns: The updated SimInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "UniqueName": unique_name, @@ -377,16 +553,17 @@ def update( "VoiceUrl": voice_url, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SimInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - async def update_async( + 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, callback_method: Union[str, object] = values.unset, @@ -406,7 +583,7 @@ async def update_async( voice_url: Union[str, object] = values.unset, ) -> SimInstance: """ - Asynchronous coroutine to update the SimInstance + Update the SimInstance :param unique_name: :param callback_method: @@ -427,48 +604,280 @@ 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._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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"]) - @property - def usage(self) -> UsageList: - """ - Access the usage + 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: """ - if self._usage is None: - self._usage = UsageList( - self._version, - self._solution["sid"], - ) - return self._usage + Update the SimInstance and return response metadata - def __repr__(self) -> str: + :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( + { + "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 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[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, + ) -> SimInstance: + """ + Asynchronous coroutine to update the SimInstance + + :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: 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, + ) + 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[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 + + :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 = 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, + ) + instance = SimInstance(self._version, payload, sid=self._solution["sid"]) + return ApiResponse(data=instance, status_code=status_code, headers=headers) + + @property + def usage(self) -> UsageList: + """ + Access the usage + """ + if self._usage is None: + self._usage = UsageList( + self._version, + self._solution["sid"], + ) + return self._usage + + def __repr__(self) -> str: """ Provide a friendly representation @@ -479,12 +888,14 @@ def __repr__(self) -> str: class SimPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: """ Build an instance of SimInstance :param payload: Payload response from the API """ + return SimInstance(self._version, payload) def __repr__(self) -> str: @@ -497,6 +908,7 @@ def __repr__(self) -> str: class SimList(ListResource): + def __init__(self, version: Version): """ Initialize the SimList @@ -592,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, @@ -621,6 +1115,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -662,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( @@ -675,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, @@ -714,7 +1290,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SimPage(self._version, response) async def page_async( @@ -756,11 +1338,115 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 de1ca5a035..33010acf35 100644 --- a/twilio/rest/preview/wireless/sim/usage.py +++ b/twilio/rest/preview/wireless/sim/usage.py @@ -12,9 +12,9 @@ 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 @@ -22,7 +22,6 @@ class UsageInstance(InstanceResource): - """ :ivar sim_sid: :ivar sim_unique_name: @@ -51,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 @@ -104,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 @@ -115,6 +151,7 @@ def __repr__(self) -> str: class UsageContext(InstanceContext): + def __init__(self, version: Version, sim_sid: str): """ Initialize the UsageContext @@ -130,66 +167,142 @@ 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 - - :param end: - :param start: + Internal helper for fetch operation - :returns: The fetched UsageInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "End": end, "Start": start, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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) - data = values.of( + 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) + """ + + params = values.of( { "End": end, "Start": start, } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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 @@ -201,6 +314,7 @@ def __repr__(self) -> str: class UsageList(ListResource): + def __init__(self, version: Version, sim_sid: str): """ Initialize the UsageList diff --git a/twilio/rest/autopilot/AutopilotBase.py b/twilio/rest/preview_iam/PreviewIamBase.py similarity index 75% rename from twilio/rest/autopilot/AutopilotBase.py rename to twilio/rest/preview_iam/PreviewIamBase.py index 3b1a7f7112..22fcbe70b1 100644 --- a/twilio/rest/autopilot/AutopilotBase.py +++ b/twilio/rest/preview_iam/PreviewIamBase.py @@ -13,23 +13,24 @@ from twilio.base.domain import Domain from twilio.rest import Client -from twilio.rest.autopilot.v1 import V1 +from twilio.rest.preview_iam.v1 import V1 -class AutopilotBase(Domain): +class PreviewIamBase(Domain): + def __init__(self, twilio: Client): """ - Initialize the Autopilot Domain + Initialize the PreviewIam Domain - :returns: Domain for Autopilot + :returns: Domain for PreviewIam """ - super().__init__(twilio, "https://autopilot.twilio.com") + super().__init__(twilio, "https://preview-iam.twilio.com") self._v1: Optional[V1] = None @property def v1(self) -> V1: """ - :returns: Versions v1 of Autopilot + :returns: Versions v1 of PreviewIam """ if self._v1 is None: self._v1 = V1(self) @@ -40,4 +41,4 @@ def __repr__(self) -> str: Provide a friendly representation :returns: Machine friendly representation """ - return "" + return "" diff --git a/twilio/rest/preview_iam/__init__.py b/twilio/rest/preview_iam/__init__.py new file mode 100644 index 0000000000..9a5bf85b24 --- /dev/null +++ b/twilio/rest/preview_iam/__init__.py @@ -0,0 +1,26 @@ +from twilio.rest.preview_iam.PreviewIamBase import PreviewIamBase + +from twilio.rest.preview_iam.v1.authorize import ( + AuthorizeList, +) +from twilio.rest.preview_iam.v1.token import ( + TokenList, +) +from twilio.rest.preview_iam.versionless.organization import ( + OrganizationList, +) +from twilio.rest.preview_iam.versionless import Versionless + + +class PreviewIam(PreviewIamBase): + @property + def organization(self) -> OrganizationList: + return Versionless(self).organization + + @property + def authorize(self) -> AuthorizeList: + return self.v1.authorize + + @property + def token(self) -> TokenList: + return self.v1.token diff --git a/twilio/rest/autopilot/v1/__init__.py b/twilio/rest/preview_iam/v1/__init__.py similarity index 50% rename from twilio/rest/autopilot/v1/__init__.py rename to twilio/rest/preview_iam/v1/__init__.py index fd23e47670..2243277793 100644 --- a/twilio/rest/autopilot/v1/__init__.py +++ b/twilio/rest/preview_iam/v1/__init__.py @@ -4,8 +4,8 @@ | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ - Twilio - Autopilot - This is the public Twilio REST API. + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) NOTE: This class is auto generated by OpenAPI Generator. https://openapi-generator.tech @@ -15,36 +15,37 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain -from twilio.rest.autopilot.v1.assistant import AssistantList -from twilio.rest.autopilot.v1.restore_assistant import RestoreAssistantList +from twilio.rest.preview_iam.v1.authorize import AuthorizeList +from twilio.rest.preview_iam.v1.token import TokenList class V1(Version): + def __init__(self, domain: Domain): """ - Initialize the V1 version of Autopilot + Initialize the V1 version of PreviewIam - :param domain: The Twilio.autopilot domain + :param domain: The Twilio.preview_iam domain """ super().__init__(domain, "v1") - self._assistants: Optional[AssistantList] = None - self._restore_assistant: Optional[RestoreAssistantList] = None + self._authorize: Optional[AuthorizeList] = None + self._token: Optional[TokenList] = None @property - def assistants(self) -> AssistantList: - if self._assistants is None: - self._assistants = AssistantList(self) - return self._assistants + def authorize(self) -> AuthorizeList: + if self._authorize is None: + self._authorize = AuthorizeList(self) + return self._authorize @property - def restore_assistant(self) -> RestoreAssistantList: - if self._restore_assistant is None: - self._restore_assistant = RestoreAssistantList(self) - return self._restore_assistant + 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 "" + return "" diff --git a/twilio/rest/preview_iam/v1/authorize.py b/twilio/rest/preview_iam/v1/authorize.py new file mode 100644 index 0000000000..e011a3d2ae --- /dev/null +++ b/twilio/rest/preview_iam/v1/authorize.py @@ -0,0 +1,221 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + 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 "" + + +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, + ) -> 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, + } + ) + + 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, + ) -> 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" + + params = values.of( + { + "response_type": response_type, + "client_id": client_id, + "redirect_uri": redirect_uri, + "scope": scope, + "state": state, + } + ) + + 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/v1/token.py b/twilio/rest/preview_iam/v1/token.py new file mode 100644 index 0000000000..9a496553a6 --- /dev/null +++ b/twilio/rest/preview_iam/v1/token.py @@ -0,0 +1,301 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + 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/preview_iam/versionless/__init__.py b/twilio/rest/preview_iam/versionless/__init__.py new file mode 100644 index 0000000000..7d6d210f14 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/__init__.py @@ -0,0 +1,43 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + 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.preview_iam.versionless.organization import OrganizationList + + +class Versionless(Version): + + def __init__(self, domain: Domain): + """ + Initialize the Versionless version of PreviewIam + + :param domain: The Twilio.preview_iam domain + """ + super().__init__(domain, "Organizations") + self._organization: Optional[OrganizationList] = None + + @property + def organization(self) -> OrganizationList: + if self._organization is None: + self._organization = OrganizationList(self) + return self._organization + + def __repr__(self) -> str: + """ + Provide a friendly representation + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/versionless/organization/__init__.py b/twilio/rest/preview_iam/versionless/organization/__init__.py new file mode 100644 index 0000000000..ce6e70e978 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/__init__.py @@ -0,0 +1,128 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + 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.instance_context import InstanceContext + +from twilio.base.list_resource import ListResource +from twilio.base.version import Version + +from twilio.rest.preview_iam.versionless.organization.account import AccountList +from twilio.rest.preview_iam.versionless.organization.role_assignment import ( + RoleAssignmentList, +) +from twilio.rest.preview_iam.versionless.organization.user import UserList + + +class OrganizationContext(InstanceContext): + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the OrganizationContext + + :param version: Version that contains the resource + :param organization_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}".format(**self._solution) + + self._accounts: Optional[AccountList] = None + self._role_assignments: Optional[RoleAssignmentList] = None + self._users: Optional[UserList] = None + + @property + def accounts(self) -> AccountList: + """ + Access the accounts + """ + if self._accounts is None: + self._accounts = AccountList( + self._version, + self._solution["organization_sid"], + ) + return self._accounts + + @property + def role_assignments(self) -> RoleAssignmentList: + """ + Access the role_assignments + """ + if self._role_assignments is None: + self._role_assignments = RoleAssignmentList( + self._version, + self._solution["organization_sid"], + ) + return self._role_assignments + + @property + def users(self) -> UserList: + """ + Access the users + """ + if self._users is None: + self._users = UserList( + self._version, + self._solution["organization_sid"], + ) + return self._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 OrganizationList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the OrganizationList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + def get(self, organization_sid: str) -> OrganizationContext: + """ + Constructs a OrganizationContext + + :param organization_sid: + """ + return OrganizationContext(self._version, organization_sid=organization_sid) + + def __call__(self, organization_sid: str) -> OrganizationContext: + """ + Constructs a OrganizationContext + + :param organization_sid: + """ + return OrganizationContext(self._version, organization_sid=organization_sid) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/versionless/organization/account.py b/twilio/rest/preview_iam/versionless/organization/account.py new file mode 100644 index 0000000000..3ee97bd283 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/account.py @@ -0,0 +1,681 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + 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 AccountInstance(InstanceResource): + """ + :ivar account_sid: Twilio account sid + :ivar friendly_name: Account friendly name + :ivar status: Account status + :ivar owner_sid: Twilio account sid + :ivar date_created: The date and time when the account was created in the system + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + account_sid: Optional[str] = None, + ): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.friendly_name: Optional[str] = payload.get("friendly_name") + 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") + ) + + self._solution = { + "organization_sid": organization_sid, + "account_sid": account_sid or self.account_sid, + } + + self._context: Optional[AccountContext] = None + + @property + def _proxy(self) -> "AccountContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: AccountContext for this AccountInstance + """ + if self._context is None: + self._context = AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + return self._context + + def fetch(self) -> "AccountInstance": + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "AccountInstance": + """ + Asynchronous coroutine to fetch the AccountInstance + + + :returns: The fetched 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountContext(InstanceContext): + + def __init__(self, version: Version, organization_sid: str, account_sid: str): + """ + Initialize the AccountContext + + :param version: Version that contains the resource + :param organization_sid: + :param account_sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "account_sid": account_sid, + } + self._uri = "/{organization_sid}/Accounts/{account_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) -> AccountInstance: + """ + Fetch the AccountInstance + + + :returns: The fetched AccountInstance + """ + payload, _, _ = self._fetch() + return AccountInstance( + self._version, + payload, + organization_sid=self._solution["organization_sid"], + account_sid=self._solution["account_sid"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccountInstance and return response metadata + + + :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" + + 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, + organization_sid=self._solution["organization_sid"], + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class AccountPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> AccountInstance: + """ + Build an instance of AccountInstance + + :param payload: Payload response from the API + """ + + return AccountInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class AccountList(ListResource): + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the AccountList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/Accounts".format(**self._solution) + + def stream( + self, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[AccountInstance]: + """ + Streams AccountInstance 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[AccountInstance]: + """ + Asynchronously streams AccountInstance 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 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, + page_size: Optional[int] = None, + ) -> List[AccountInstance]: + """ + Lists AccountInstance 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[AccountInstance]: + """ + Asynchronously lists AccountInstance 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 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, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> AccountPage: + """ + Retrieve a single page of AccountInstance 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 AccountInstance + """ + data = values.of( + { + "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 AccountPage(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, + ) -> AccountPage: + """ + Asynchronously retrieve a single page of AccountInstance 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 AccountInstance + """ + data = values.of( + { + "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 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: + """ + Retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return AccountPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> AccountPage: + """ + Asynchronously retrieve a specific page of AccountInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of AccountInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return AccountPage(self._version, response, solution=self._solution) + + def get(self, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param account_sid: + """ + return AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=account_sid, + ) + + def __call__(self, account_sid: str) -> AccountContext: + """ + Constructs a AccountContext + + :param account_sid: + """ + return AccountContext( + self._version, + organization_sid=self._solution["organization_sid"], + account_sid=account_sid, + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/versionless/organization/role_assignment.py b/twilio/rest/preview_iam/versionless/organization/role_assignment.py new file mode 100644 index 0000000000..860b077723 --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/role_assignment.py @@ -0,0 +1,1011 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + 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 RoleAssignmentInstance(InstanceResource): + + 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]): + + 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, + } + + """ + :ivar sid: Twilio Role Assignment Sid representing this role assignment + :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 + :ivar status: HTTP response status code + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + sid: Optional[str] = None, + ): + super().__init__(version) + + self.sid: Optional[str] = payload.get("sid") + 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") + self.status: Optional[int] = payload.get("status") + + self._solution = { + "organization_sid": organization_sid, + "sid": sid or self.sid, + } + + self._context: Optional[RoleAssignmentContext] = None + + @property + def _proxy(self) -> "RoleAssignmentContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: RoleAssignmentContext for this RoleAssignmentInstance + """ + if self._context is None: + self._context = RoleAssignmentContext( + self._version, + organization_sid=self._solution["organization_sid"], + sid=self._solution["sid"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the RoleAssignmentInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class RoleAssignmentContext(InstanceContext): + + 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]): + + 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): + """ + Initialize the RoleAssignmentContext + + :param version: Version that contains the resource + :param organization_sid: + :param sid: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "sid": sid, + } + 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 + + + :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 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 RoleAssignmentInstance + + + :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 RoleAssignmentInstance 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 __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 RoleAssignmentPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> RoleAssignmentInstance: + """ + Build an instance of RoleAssignmentInstance + + :param payload: Payload response from the API + """ + + return RoleAssignmentInstance( + self._version, payload, organization_sid=self._solution["organization_sid"] + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class RoleAssignmentList(ListResource): + + 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]): + + 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): + """ + Initialize the RoleAssignmentList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/RoleAssignments".format(**self._solution) + + def _create( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = public_api_create_role_assignment_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, + 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"] + ) + + def create_with_http_info( + self, + public_api_create_role_assignment_request: PublicApiCreateRoleAssignmentRequest, + ) -> ApiResponse: + """ + 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 = 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() + + 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, + 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]: + """ + Streams RoleAssignmentInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, 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"]) + + 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]: + """ + Asynchronously streams RoleAssignmentInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async( + 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]: + """ + Lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: 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, + ) + ) + + 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]: + """ + Asynchronously lists RoleAssignmentInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: 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, + ) -> RoleAssignmentPage: + """ + Retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :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: Page of RoleAssignmentInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + ) -> RoleAssignmentPage: + """ + Asynchronously retrieve a single page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :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: Page of RoleAssignmentInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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: + """ + Retrieve a specific page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleAssignmentInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return RoleAssignmentPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> RoleAssignmentPage: + """ + Asynchronously retrieve a specific page of RoleAssignmentInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of RoleAssignmentInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return RoleAssignmentPage(self._version, response, solution=self._solution) + + def get(self, sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param sid: + """ + return RoleAssignmentContext( + self._version, organization_sid=self._solution["organization_sid"], sid=sid + ) + + def __call__(self, sid: str) -> RoleAssignmentContext: + """ + Constructs a RoleAssignmentContext + + :param sid: + """ + return RoleAssignmentContext( + self._version, organization_sid=self._solution["organization_sid"], sid=sid + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/preview_iam/versionless/organization/user.py b/twilio/rest/preview_iam/versionless/organization/user.py new file mode 100644 index 0000000000..8299913b2c --- /dev/null +++ b/twilio/rest/preview_iam/versionless/organization/user.py @@ -0,0 +1,1830 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Organization Public API + No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + + 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 values +from twilio.base.api_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 UserInstance(InstanceResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resourceType") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("lastModified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resourceType": self.resource_type, + "created": self.created, + "lastModified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + 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 { + "schemas": self.schemas, + "Operations": ( + [operations.to_dict() for operations in self.operations] + if self.operations is not None + else None + ), + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + 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" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + 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["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") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + organization_sid: str, + id: Optional[str] = None, + ): + super().__init__(version) + + self.id: Optional[str] = payload.get("id") + 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.str] = payload.get("name") + self.emails: Optional[List[UserList.str]] = payload.get("emails") + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + 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["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") + + self._solution = { + "organization_sid": organization_sid, + "id": id or self.id, + } + + self._context: Optional[UserContext] = None + + @property + def _proxy(self) -> "UserContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: UserContext for this UserInstance + """ + if self._context is None: + self._context = UserContext( + self._version, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + return self._context + + def delete(self) -> bool: + """ + Deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + return self._proxy.delete() + + async def delete_async(self) -> bool: + """ + Asynchronous coroutine that deletes the UserInstance + + + :returns: True if delete succeeds, False otherwise + """ + 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 + + + :returns: The fetched UserInstance + """ + return self._proxy.fetch() + + async def fetch_async(self) -> "UserInstance": + """ + Asynchronous coroutine to fetch the UserInstance + + + :returns: The fetched 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": + """ + Update the UserInstance + + :param scim_user: + :param if_match: + + :returns: The updated UserInstance + """ + return self._proxy.update( + scim_user=scim_user, + if_match=if_match, + ) + + 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 + """ + return await self._proxy.update_async( + scim_user=scim_user, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class UserContext(InstanceContext): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resourceType") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("lastModified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resourceType": self.resource_type, + "created": self.created, + "lastModified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + 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 { + "schemas": self.schemas, + "Operations": ( + [operations.to_dict() for operations in self.operations] + if self.operations is not None + else None + ), + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + 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" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + 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["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") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + def __init__(self, version: Version, organization_sid: str, id: str): + """ + Initialize the UserContext + + :param version: Version that contains the resource + :param organization_sid: + :param id: + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + "id": id, + } + 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 + + + :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 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 UserInstance + + + :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 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, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the UserInstance and return response metadata + + + :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) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + headers = values.of({}) + + headers["Accept"] = "application/scim+json" + + 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, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + 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, + 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({}) + + 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.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, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + def patch_with_http_info( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Patch the UserInstance and return response metadata + + :param scim_patch_request: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + 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({}) + + 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.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, + organization_sid=self._solution["organization_sid"], + id=self._solution["id"], + ) + + async def patch_with_http_info_async( + self, + scim_patch_request: ScimPatchRequest, + if_match: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronous coroutine to patch the UserInstance and return response metadata + + :param scim_patch_request: + :param if_match: + + :returns: ApiResponse with instance, status code, and headers + """ + 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 _update( + self, scim_user: ScimUser, if_match: Union[str, object] = values.unset + ) -> tuple: + """ + Internal 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 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 "".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 "" + + +class UserList(ListResource): + + class ScimEmailAddress(object): + """ + :ivar primary: Indicates if this email address is the primary one + :ivar value: The actual email address value + :ivar type: The type of email address (e.g., work, home, etc.) + """ + + def __init__(self, payload: Dict[str, Any]): + + self.primary: Optional[bool] = payload.get("primary") + self.value: Optional[str] = payload.get("value") + self.type: Optional[str] = payload.get("type") + + def to_dict(self): + return { + "primary": self.primary, + "value": self.value, + "type": self.type, + } + + class ScimMeta(object): + """ + :ivar resource_type: Indicates the type of the resource + :ivar created: The date and time when the resource was created in the system + :ivar last_modified: The date and time when the resource was last modified + :ivar version: A version identifier for the resource. This can be used to manage resource versioning and concurrency control. + """ + + def __init__(self, payload: Dict[str, Any]): + + self.resource_type: Optional[str] = payload.get("resourceType") + self.created: Optional[datetime] = payload.get("created") + self.last_modified: Optional[datetime] = payload.get("lastModified") + self.version: Optional[str] = payload.get("version") + + def to_dict(self): + return { + "resourceType": self.resource_type, + "created": self.created, + "lastModified": self.last_modified, + "version": self.version, + } + + class ScimName(object): + """ + :ivar given_name: The user's first or given name + :ivar family_name: The user's last or family name + """ + + def __init__(self, payload: Dict[str, Any]): + + 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 { + "schemas": self.schemas, + "Operations": ( + [operations.to_dict() for operations in self.operations] + if self.operations is not None + else None + ), + } + + class ScimUser(object): + """ + :ivar id: Unique Twilio user sid + :ivar external_id: External unique resource id defined by provisioning client + :ivar user_name: Unique username, MUST be same as primary email address + :ivar display_name: User friendly display name + :ivar name: + :ivar emails: Email address list of the user. Primary email must be defined if there are more than 1 email. Primary email must match the username. + :ivar active: Indicates whether the user is active + :ivar locale: User's locale + :ivar timezone: User's time zone + :ivar schemas: An array of URIs that indicate the schemas supported for this user resource + :ivar meta: + :ivar detail: A human-readable description of the error + :ivar scim_type: A scimType error code as defined in RFC7644 + :ivar status: Http status code + :ivar code: Twilio-specific error code + :ivar more_info: Link to Error Code References + """ + + def __init__(self, payload: Dict[str, Any]): + + self.id: Optional[str] = payload.get("id") + 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" + ) + self.active: Optional[bool] = payload.get("active") + self.locale: Optional[str] = payload.get("locale") + self.timezone: Optional[str] = payload.get("timezone") + 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["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") + + def to_dict(self): + return { + "id": self.id, + "externalId": self.external_id, + "userName": self.user_name, + "displayName": self.display_name, + "name": self.name.to_dict() if self.name is not None else None, + "emails": ( + [emails.to_dict() for emails in self.emails] + if self.emails is not None + else None + ), + "active": self.active, + "locale": self.locale, + "timezone": self.timezone, + "schemas": self.schemas, + "meta": self.meta.to_dict() if self.meta is not None else None, + "detail": self.detail, + "scimType": self.scim_type, + "status": self.status, + "code": self.code, + "moreInfo": self.more_info, + } + + def __init__(self, version: Version, organization_sid: str): + """ + Initialize the UserList + + :param version: Version that contains the resource + :param organization_sid: + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "organization_sid": organization_sid, + } + self._uri = "/{organization_sid}/scim/Users".format(**self._solution) + + def _create(self, scim_user: ScimUser) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + data = scim_user.to_dict() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + 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"] + ) + + def create_with_http_info(self, scim_user: ScimUser) -> ApiResponse: + """ + Create the UserInstance and return response metadata + + :param scim_user: + + :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() + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/json" + + headers["Content-Type"] = "application/scim+json" + + headers["Accept"] = "application/scim+json" + + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> Iterator[UserInstance]: + """ + Streams UserInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = self.page(filter=filter, page_size=limits["page_size"]) + + return self._version.stream(page, limits["limit"]) + + async def stream_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> AsyncIterator[UserInstance]: + """ + Asynchronously streams UserInstance 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 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: Generator that will yield up to limit results + """ + limits = self._version.read_limits(limit, page_size) + page = await self.page_async(filter=filter, page_size=limits["page_size"]) + + 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, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return list( + self.stream( + filter=filter, + limit=limit, + page_size=page_size, + ) + ) + + async def list_async( + self, + filter: Union[str, object] = values.unset, + limit: Optional[int] = None, + page_size: Optional[int] = None, + ) -> List[UserInstance]: + """ + Asynchronously lists UserInstance records from the API as a list. + Unlike stream(), this operation is eager and will load `limit` records into + memory before returning. + + :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: list that will contain up to limit results + """ + + return [ + record + async for record in await self.stream_async( + filter=filter, + limit=limit, + page_size=page_size, + ) + ] + + 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, + page_token: Union[str, object] = values.unset, + page_number: Union[int, object] = values.unset, + page_size: Union[int, object] = values.unset, + ) -> UserPage: + """ + Retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :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: Page of UserInstance + """ + 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 = self._version.page( + method="GET", uri=self._uri, params=data, headers=headers + ) + return UserPage(self._version, response, solution=self._solution) + + async def page_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, + ) -> UserPage: + """ + Asynchronously retrieve a single page of UserInstance records from the API. + Request is executed immediately + + :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: Page of UserInstance + """ + 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 = await self._version.page_async( + method="GET", uri=self._uri, params=data, headers=headers + ) + 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: + """ + Retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = self._version.domain.twilio.request("GET", target_url) + return UserPage(self._version, response, solution=self._solution) + + async def get_page_async(self, target_url: str) -> UserPage: + """ + Asynchronously retrieve a specific page of UserInstance records from the API. + Request is executed immediately + + :param target_url: API-generated URL for the requested results page + + :returns: Page of UserInstance + """ + response = await self._version.domain.twilio.request_async("GET", target_url) + return UserPage(self._version, response, solution=self._solution) + + def get(self, id: str) -> UserContext: + """ + Constructs a UserContext + + :param id: + """ + return UserContext( + self._version, organization_sid=self._solution["organization_sid"], id=id + ) + + def __call__(self, id: str) -> UserContext: + """ + Constructs a UserContext + + :param id: + """ + return UserContext( + self._version, organization_sid=self._solution["organization_sid"], id=id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/pricing/PricingBase.py b/twilio/rest/pricing/PricingBase.py index 35028ee350..cf624e1867 100644 --- a/twilio/rest/pricing/PricingBase.py +++ b/twilio/rest/pricing/PricingBase.py @@ -18,6 +18,7 @@ class PricingBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Pricing Domain diff --git a/twilio/rest/pricing/v1/__init__.py b/twilio/rest/pricing/v1/__init__.py index 2227d163d4..ba8b65885d 100644 --- a/twilio/rest/pricing/v1/__init__.py +++ b/twilio/rest/pricing/v1/__init__.py @@ -21,6 +21,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Pricing diff --git a/twilio/rest/pricing/v1/messaging/__init__.py b/twilio/rest/pricing/v1/messaging/__init__.py index 32230c7135..df5c148b81 100644 --- a/twilio/rest/pricing/v1/messaging/__init__.py +++ b/twilio/rest/pricing/v1/messaging/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -23,6 +22,7 @@ class MessagingList(ListResource): + def __init__(self, version: Version): """ Initialize the MessagingList diff --git a/twilio/rest/pricing/v1/messaging/country.py b/twilio/rest/pricing/v1/messaging/country.py index fba539fc68..ecb387919d 100644 --- a/twilio/rest/pricing/v1/messaging/country.py +++ b/twilio/rest/pricing/v1/messaging/country.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class CountryInstance(InstanceResource): - """ :ivar country: The name of the country. :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). @@ -53,6 +52,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -88,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 @@ -99,6 +117,7 @@ def __repr__(self) -> str: class CountryContext(InstanceContext): + def __init__(self, version: Version, iso_country: str): """ Initialize the CountryContext @@ -114,6 +133,22 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/Messaging/Countries/{iso_country}".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) -> CountryInstance: """ Fetch the CountryInstance @@ -121,17 +156,43 @@ def fetch(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CountryInstance: """ @@ -140,17 +201,27 @@ async def fetch_async(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + 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: """ @@ -163,12 +234,14 @@ def __repr__(self) -> str: class CountryPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -181,6 +254,7 @@ def __repr__(self) -> str: class CountryList(ListResource): + def __init__(self, version: Version): """ Initialize the CountryList @@ -242,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, @@ -261,6 +385,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -287,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( @@ -295,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, @@ -319,7 +495,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CountryPage(self._version, response) async def page_async( @@ -346,11 +528,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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/__init__.py b/twilio/rest/pricing/v1/phone_number/__init__.py index b3cfbe50e4..429ce9b14c 100644 --- a/twilio/rest/pricing/v1/phone_number/__init__.py +++ b/twilio/rest/pricing/v1/phone_number/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -23,6 +22,7 @@ class PhoneNumberList(ListResource): + def __init__(self, version: Version): """ Initialize the PhoneNumberList diff --git a/twilio/rest/pricing/v1/phone_number/country.py b/twilio/rest/pricing/v1/phone_number/country.py index 30a0eeb475..7775696a6d 100644 --- a/twilio/rest/pricing/v1/phone_number/country.py +++ b/twilio/rest/pricing/v1/phone_number/country.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class CountryInstance(InstanceResource): - """ :ivar country: The name of the country. :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). @@ -51,6 +50,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -86,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 @@ -97,6 +115,7 @@ def __repr__(self) -> str: class CountryContext(InstanceContext): + def __init__(self, version: Version, iso_country: str): """ Initialize the CountryContext @@ -112,6 +131,22 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/PhoneNumbers/Countries/{iso_country}".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) -> CountryInstance: """ Fetch the CountryInstance @@ -119,17 +154,43 @@ def fetch(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CountryInstance: """ @@ -138,17 +199,27 @@ async def fetch_async(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + 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: """ @@ -161,12 +232,14 @@ def __repr__(self) -> str: class CountryPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -179,6 +252,7 @@ def __repr__(self) -> str: class CountryList(ListResource): + def __init__(self, version: Version): """ Initialize the CountryList @@ -240,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, @@ -259,6 +383,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -285,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( @@ -293,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, @@ -317,7 +493,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CountryPage(self._version, response) async def page_async( @@ -344,11 +526,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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/__init__.py b/twilio/rest/pricing/v1/voice/__init__.py index 4d91f382c9..a801a30089 100644 --- a/twilio/rest/pricing/v1/voice/__init__.py +++ b/twilio/rest/pricing/v1/voice/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -24,6 +23,7 @@ class VoiceList(ListResource): + def __init__(self, version: Version): """ Initialize the VoiceList diff --git a/twilio/rest/pricing/v1/voice/country.py b/twilio/rest/pricing/v1/voice/country.py index c65df83f41..600488ab44 100644 --- a/twilio/rest/pricing/v1/voice/country.py +++ b/twilio/rest/pricing/v1/voice/country.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class CountryInstance(InstanceResource): - """ :ivar country: The name of the country. :ivar iso_country: The [ISO country code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). @@ -55,6 +54,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -90,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 @@ -101,6 +119,7 @@ def __repr__(self) -> str: class CountryContext(InstanceContext): + def __init__(self, version: Version, iso_country: str): """ Initialize the CountryContext @@ -116,6 +135,22 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/Voice/Countries/{iso_country}".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) -> CountryInstance: """ Fetch the CountryInstance @@ -123,17 +158,43 @@ def fetch(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CountryInstance: """ @@ -142,17 +203,27 @@ async def fetch_async(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + 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: """ @@ -165,12 +236,14 @@ def __repr__(self) -> str: class CountryPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -183,6 +256,7 @@ def __repr__(self) -> str: class CountryList(ListResource): + def __init__(self, version: Version): """ Initialize the CountryList @@ -244,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, @@ -263,6 +387,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -289,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( @@ -297,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, @@ -321,7 +497,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CountryPage(self._version, response) async def page_async( @@ -348,11 +530,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 dfdf4b63f8..5dab5e2dd0 100644 --- a/twilio/rest/pricing/v1/voice/number.py +++ b/twilio/rest/pricing/v1/voice/number.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class NumberInstance(InstanceResource): - """ :ivar number: The phone number. :ivar country: The name of the country. @@ -48,6 +48,7 @@ def __init__( self._solution = { "number": number or self.number, } + self._context: Optional[NumberContext] = None @property @@ -83,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 @@ -94,6 +113,7 @@ def __repr__(self) -> str: class NumberContext(InstanceContext): + def __init__(self, version: Version, number: str): """ Initialize the NumberContext @@ -109,6 +129,22 @@ def __init__(self, version: Version, number: str): } self._uri = "/Voice/Numbers/{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) -> NumberInstance: """ Fetch the NumberInstance @@ -116,17 +152,43 @@ def fetch(self) -> NumberInstance: :returns: The fetched NumberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return NumberInstance( + self._version, + payload, + number=self._solution["number"], ) - return NumberInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NumberInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> NumberInstance: """ @@ -135,17 +197,27 @@ async def fetch_async(self) -> NumberInstance: :returns: The fetched NumberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return NumberInstance( + self._version, + payload, + number=self._solution["number"], ) - return NumberInstance( + 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: """ @@ -158,6 +230,7 @@ def __repr__(self) -> str: class NumberList(ListResource): + def __init__(self, version: Version): """ Initialize the NumberList diff --git a/twilio/rest/pricing/v2/__init__.py b/twilio/rest/pricing/v2/__init__.py index f034595cb2..d0fd67f737 100644 --- a/twilio/rest/pricing/v2/__init__.py +++ b/twilio/rest/pricing/v2/__init__.py @@ -21,6 +21,7 @@ class V2(Version): + def __init__(self, domain: Domain): """ Initialize the V2 version of Pricing diff --git a/twilio/rest/pricing/v2/country.py b/twilio/rest/pricing/v2/country.py index 6842359b88..94cdd8a272 100644 --- a/twilio/rest/pricing/v2/country.py +++ b/twilio/rest/pricing/v2/country.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class CountryInstance(InstanceResource): - """ :ivar country: The name of the country. :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). @@ -55,6 +54,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -90,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 @@ -101,6 +119,7 @@ def __repr__(self) -> str: class CountryContext(InstanceContext): + def __init__(self, version: Version, iso_country: str): """ Initialize the CountryContext @@ -116,6 +135,22 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/Trunking/Countries/{iso_country}".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) -> CountryInstance: """ Fetch the CountryInstance @@ -123,17 +158,43 @@ def fetch(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CountryInstance: """ @@ -142,17 +203,27 @@ async def fetch_async(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + 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: """ @@ -165,12 +236,14 @@ def __repr__(self) -> str: class CountryPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -183,6 +256,7 @@ def __repr__(self) -> str: class CountryList(ListResource): + def __init__(self, version: Version): """ Initialize the CountryList @@ -244,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, @@ -263,6 +387,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -289,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( @@ -297,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, @@ -321,7 +497,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CountryPage(self._version, response) async def page_async( @@ -348,11 +530,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 39d8eb4783..eddd2b6ef5 100644 --- a/twilio/rest/pricing/v2/number.py +++ b/twilio/rest/pricing/v2/number.py @@ -12,9 +12,9 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,7 +22,6 @@ class NumberInstance(InstanceResource): - """ :ivar destination_number: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. :ivar origination_number: The origination phone number in [[E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. @@ -58,6 +57,7 @@ def __init__( self._solution = { "destination_number": destination_number or self.destination_number, } + self._context: Optional[NumberContext] = None @property @@ -103,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 @@ -114,6 +142,7 @@ def __repr__(self) -> str: class NumberContext(InstanceContext): + def __init__(self, version: Version, destination_number: str): """ Initialize the NumberContext @@ -129,6 +158,28 @@ 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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "OriginationNumber": origination_number, + } + ) + + 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, origination_number: Union[str, object] = values.unset ) -> NumberInstance: @@ -139,19 +190,55 @@ def fetch( :returns: The fetched NumberInstance """ + payload, _, _ = self._fetch(origination_number=origination_number) + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) - data = values.of( + def fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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) + """ + + params = values.of( { "OriginationNumber": origination_number, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + headers = values.of({}) - return NumberInstance( - self._version, - payload, - destination_number=self._solution["destination_number"], + 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( @@ -164,22 +251,32 @@ async def fetch_async( :returns: The fetched NumberInstance """ - - data = values.of( - { - "OriginationNumber": origination_number, - } + payload, _, _ = await self._fetch_async(origination_number=origination_number) + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return 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: 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: """ @@ -192,6 +289,7 @@ def __repr__(self) -> str: class NumberList(ListResource): + def __init__(self, version: Version): """ Initialize the NumberList diff --git a/twilio/rest/pricing/v2/voice/__init__.py b/twilio/rest/pricing/v2/voice/__init__.py index 6539469636..1ebbcbb644 100644 --- a/twilio/rest/pricing/v2/voice/__init__.py +++ b/twilio/rest/pricing/v2/voice/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -24,6 +23,7 @@ class VoiceList(ListResource): + def __init__(self, version: Version): """ Initialize the VoiceList diff --git a/twilio/rest/pricing/v2/voice/country.py b/twilio/rest/pricing/v2/voice/country.py index a06ed0a762..303e8d8522 100644 --- a/twilio/rest/pricing/v2/voice/country.py +++ b/twilio/rest/pricing/v2/voice/country.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class CountryInstance(InstanceResource): - """ :ivar country: The name of the country. :ivar iso_country: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). @@ -55,6 +54,7 @@ def __init__( self._solution = { "iso_country": iso_country or self.iso_country, } + self._context: Optional[CountryContext] = None @property @@ -90,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 @@ -101,6 +119,7 @@ def __repr__(self) -> str: class CountryContext(InstanceContext): + def __init__(self, version: Version, iso_country: str): """ Initialize the CountryContext @@ -116,6 +135,22 @@ def __init__(self, version: Version, iso_country: str): } self._uri = "/Voice/Countries/{iso_country}".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) -> CountryInstance: """ Fetch the CountryInstance @@ -123,17 +158,43 @@ def fetch(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CountryInstance: """ @@ -142,17 +203,27 @@ async def fetch_async(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_country=self._solution["iso_country"], ) - return CountryInstance( + 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: """ @@ -165,12 +236,14 @@ def __repr__(self) -> str: class CountryPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -183,6 +256,7 @@ def __repr__(self) -> str: class CountryList(ListResource): + def __init__(self, version: Version): """ Initialize the CountryList @@ -244,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, @@ -263,6 +387,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -289,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( @@ -297,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, @@ -321,7 +497,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CountryPage(self._version, response) async def page_async( @@ -348,11 +530,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 6d4f1bddb3..516e6f4cb4 100644 --- a/twilio/rest/pricing/v2/voice/number.py +++ b/twilio/rest/pricing/v2/voice/number.py @@ -12,9 +12,9 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,7 +22,6 @@ class NumberInstance(InstanceResource): - """ :ivar destination_number: The destination phone number in [E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. :ivar origination_number: The origination phone number in [[E.164](https://www.twilio.com/docs/glossary/what-e164) format, which consists of a + followed by the country code and subscriber number. @@ -56,6 +55,7 @@ def __init__( self._solution = { "destination_number": destination_number or self.destination_number, } + self._context: Optional[NumberContext] = None @property @@ -101,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 @@ -112,6 +140,7 @@ def __repr__(self) -> str: class NumberContext(InstanceContext): + def __init__(self, version: Version, destination_number: str): """ Initialize the NumberContext @@ -127,6 +156,28 @@ 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) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "OriginationNumber": origination_number, + } + ) + + 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, origination_number: Union[str, object] = values.unset ) -> NumberInstance: @@ -137,19 +188,55 @@ def fetch( :returns: The fetched NumberInstance """ + payload, _, _ = self._fetch(origination_number=origination_number) + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], + ) - data = values.of( + def fetch_with_http_info( + self, origination_number: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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) + """ + + params = values.of( { "OriginationNumber": origination_number, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + headers = values.of({}) - return NumberInstance( - self._version, - payload, - destination_number=self._solution["destination_number"], + 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( @@ -162,22 +249,32 @@ async def fetch_async( :returns: The fetched NumberInstance """ - - data = values.of( - { - "OriginationNumber": origination_number, - } + payload, _, _ = await self._fetch_async(origination_number=origination_number) + return NumberInstance( + self._version, + payload, + destination_number=self._solution["destination_number"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return 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: 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: """ @@ -190,6 +287,7 @@ def __repr__(self) -> str: class NumberList(ListResource): + def __init__(self, version: Version): """ Initialize the NumberList diff --git a/twilio/rest/proxy/ProxyBase.py b/twilio/rest/proxy/ProxyBase.py index b4d4d0e84d..da1baec178 100644 --- a/twilio/rest/proxy/ProxyBase.py +++ b/twilio/rest/proxy/ProxyBase.py @@ -17,6 +17,7 @@ class ProxyBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Proxy Domain diff --git a/twilio/rest/proxy/v1/__init__.py b/twilio/rest/proxy/v1/__init__.py index 87a58d3ff2..83737dc0fb 100644 --- a/twilio/rest/proxy/v1/__init__.py +++ b/twilio/rest/proxy/v1/__init__.py @@ -19,6 +19,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Proxy diff --git a/twilio/rest/proxy/v1/service/__init__.py b/twilio/rest/proxy/v1/service/__init__.py index a86444ebe4..82b845dfb5 100644 --- a/twilio/rest/proxy/v1/service/__init__.py +++ b/twilio/rest/proxy/v1/service/__init__.py @@ -12,10 +12,10 @@ 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 @@ -23,10 +23,10 @@ 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): + class GeoMatchLevel(object): AREA_CODE = "area-code" OVERLAY = "overlay" @@ -47,7 +47,7 @@ class NumberSelectionBehavior(object): :ivar number_selection_behavior: :ivar geo_match_level: :ivar intercept_callback_url: The URL we call on each interaction. If we receive a 403 status, we block the interaction; otherwise the interaction continues. - :ivar out_of_session_callback_url: The URL we 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/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. + :ivar out_of_session_callback_url: The URL we 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. :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 url: The absolute URL of the Service resource. @@ -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, @@ -166,7 +203,7 @@ def update( :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/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 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 @@ -204,7 +241,7 @@ async def update_async( :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/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 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 @@ -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 @@ -252,6 +358,7 @@ def __repr__(self) -> str: class ServiceContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ServiceContext @@ -269,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: """ @@ -278,9 +398,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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: @@ -290,9 +432,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -302,17 +468,43 @@ def fetch(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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: """ @@ -321,19 +513,29 @@ async def fetch_async(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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( + def _update( self, unique_name: Union[str, object] = values.unset, default_ttl: Union[int, object] = values.unset, @@ -345,21 +547,14 @@ 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/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( { "UniqueName": unique_name, @@ -372,16 +567,17 @@ def update( "ChatInstanceSid": chat_instance_sid, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - async def update_async( + 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, default_ttl: Union[int, object] = values.unset, @@ -395,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. @@ -403,11 +599,83 @@ async def update_async( :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/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 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, _, _ = 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( { "UniqueName": unique_name, @@ -420,50 +688,118 @@ async def update_async( "ChatInstanceSid": chat_instance_sid, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + headers["Content-Type"] = "application/x-www-form-urlencoded" - @property - def phone_numbers(self) -> PhoneNumberList: - """ - Access the phone_numbers - """ - if self._phone_numbers is None: - self._phone_numbers = PhoneNumberList( - self._version, - self._solution["sid"], - ) - return self._phone_numbers + headers["Accept"] = "application/json" - @property - def sessions(self) -> SessionList: - """ - Access the sessions - """ - if self._sessions is None: - self._sessions = SessionList( - self._version, - self._solution["sid"], - ) - return self._sessions + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property - def short_codes(self) -> ShortCodeList: + 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: + """ + 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: """ - Access the short_codes + 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 """ - if self._short_codes is None: - self._short_codes = ShortCodeList( + 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 phone_numbers(self) -> PhoneNumberList: + """ + Access the phone_numbers + """ + if self._phone_numbers is None: + self._phone_numbers = PhoneNumberList( + self._version, + self._solution["sid"], + ) + return self._phone_numbers + + @property + def sessions(self) -> SessionList: + """ + Access the sessions + """ + if self._sessions is None: + self._sessions = SessionList( self._version, self._solution["sid"], ) - return self._short_codes + return self._sessions def __repr__(self) -> str: """ @@ -476,12 +812,14 @@ def __repr__(self) -> str: 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: @@ -494,6 +832,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -505,6 +844,48 @@ def __init__(self, version: Version): self._uri = "/Services" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "DefaultTtl": default_ttl, + "CallbackUrl": callback_url, + "GeoMatchLevel": geo_match_level, + "NumberSelectionBehavior": number_selection_behavior, + "InterceptCallbackUrl": intercept_callback_url, + "OutOfSessionCallbackUrl": out_of_session_callback_url, + "ChatInstanceSid": chat_instance_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, unique_name: str, @@ -527,11 +908,83 @@ def create( :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/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 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, _, _ = 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( { "UniqueName": unique_name, @@ -544,14 +997,15 @@ def create( "ChatInstanceSid": chat_instance_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(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, @@ -575,31 +1029,62 @@ async def create_async( :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/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 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 """ - data = values.of( - { - "UniqueName": unique_name, - "DefaultTtl": default_ttl, - "CallbackUrl": callback_url, - "GeoMatchLevel": geo_match_level, - "NumberSelectionBehavior": number_selection_behavior, - "InterceptCallbackUrl": intercept_callback_url, - "OutOfSessionCallbackUrl": out_of_session_callback_url, - "ChatInstanceSid": chat_instance_sid, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return ServiceInstance(self._version, payload) + :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, @@ -651,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, @@ -670,6 +1205,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -696,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( @@ -704,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, @@ -728,7 +1315,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -755,11 +1348,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 fc8c514f13..8d206f2e06 100644 --- a/twilio/rest/proxy/v1/service/phone_number.py +++ b/twilio/rest/proxy/v1/service/phone_number.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class PhoneNumberInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the PhoneNumber resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the PhoneNumber resource. @@ -70,6 +69,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[PhoneNumberContext] = None @property @@ -106,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 @@ -124,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": @@ -152,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 @@ -163,6 +227,7 @@ def __repr__(self) -> str: class PhoneNumberContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the PhoneNumberContext @@ -182,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 @@ -189,9 +268,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -201,9 +302,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance 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) -> PhoneNumberInstance: @@ -213,18 +338,45 @@ def fetch(self) -> PhoneNumberInstance: :returns: The fetched PhoneNumberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return PhoneNumberInstance( + 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, 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) -> PhoneNumberInstance: """ @@ -233,18 +385,52 @@ async def fetch_async(self) -> PhoneNumberInstance: :returns: The fetched PhoneNumberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return PhoneNumberInstance( + 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 _update(self, is_reserved: Union[bool, object] = values.unset) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + 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" + + 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 @@ -256,24 +442,57 @@ def update( :returns: The updated PhoneNumberInstance """ - data = values.of( - { - "IsReserved": is_reserved, - } + payload, _, _ = self._update(is_reserved=is_reserved) + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + def update_with_http_info( + self, is_reserved: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + Update the PhoneNumberInstance and return response metadata - return 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: 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( + { + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + 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, is_reserved: Union[bool, object] = values.unset @@ -285,24 +504,34 @@ async def update_async( :returns: The updated PhoneNumberInstance """ - data = values.of( - { - "IsReserved": is_reserved, - } + payload, _, _ = await self._update_async(is_reserved=is_reserved) + return PhoneNumberInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return 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: 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: """ @@ -315,12 +544,14 @@ def __repr__(self) -> str: class PhoneNumberPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: """ Build an instance of PhoneNumberInstance :param payload: Payload response from the API """ + return PhoneNumberInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -335,6 +566,7 @@ def __repr__(self) -> str: class PhoneNumberList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the PhoneNumberList @@ -351,6 +583,36 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/PhoneNumbers".format(**self._solution) + def _create( + self, + sid: Union[str, object] = values.unset, + phone_number: Union[str, object] = values.unset, + is_reserved: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Sid": sid, + "PhoneNumber": phone_number, + "IsReserved": serialize.boolean_to_string(is_reserved), + } + ) + 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, sid: Union[str, object] = values.unset, @@ -366,22 +628,64 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "Sid": sid, "PhoneNumber": phone_number, - "IsReserved": is_reserved, + "IsReserved": serialize.boolean_to_string(is_reserved), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return PhoneNumberInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -399,23 +703,35 @@ async def create_async( :returns: The created PhoneNumberInstance """ - data = values.of( - { - "Sid": sid, - "PhoneNumber": phone_number, - "IsReserved": is_reserved, - } + payload, _, _ = await self._create_async( + sid=sid, phone_number=phone_number, is_reserved=is_reserved ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return PhoneNumberInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return PhoneNumberInstance( + 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, @@ -467,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, @@ -486,6 +852,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -512,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( @@ -520,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, @@ -544,8 +962,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return PhoneNumberPage(self._version, response, self._solution) + 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 PhoneNumberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -571,10 +995,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return PhoneNumberPage(self._version, response, self._solution) + 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: """ @@ -586,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: """ @@ -598,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 7ce76fcab5..ba7ee376b3 100644 --- a/twilio/rest/proxy/v1/service/session/__init__.py +++ b/twilio/rest/proxy/v1/service/session/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,6 +26,7 @@ class SessionInstance(InstanceResource): + class Mode(object): MESSAGE_ONLY = "message-only" VOICE_ONLY = "voice-only" @@ -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: """ @@ -220,6 +300,7 @@ def __repr__(self) -> str: class SessionContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the SessionContext @@ -240,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 @@ -247,9 +342,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -259,9 +376,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SessionInstance 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) -> SessionInstance: @@ -271,18 +412,45 @@ def fetch(self) -> SessionInstance: :returns: The fetched SessionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return SessionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SessionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SessionInstance: """ @@ -291,34 +459,43 @@ async def fetch_async(self) -> SessionInstance: :returns: The fetched SessionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SessionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return SessionInstance( + 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( + 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 - - :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: + Internal helper for update operation - :returns: The updated SessionInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "DateExpiry": serialize.iso8601_datetime(date_expiry), @@ -326,13 +503,32 @@ def update( "Status": status, } ) + 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, + 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, @@ -340,21 +536,45 @@ 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( { "DateExpiry": serialize.iso8601_datetime(date_expiry), @@ -362,13 +582,34 @@ async def update_async( "Status": status, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -376,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: """ @@ -413,12 +680,14 @@ def __repr__(self) -> str: 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, service_sid=self._solution["service_sid"] ) @@ -433,6 +702,7 @@ def __repr__(self) -> str: class SessionList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the SessionList @@ -449,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, @@ -457,19 +727,14 @@ 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 + 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 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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "UniqueName": unique_name, @@ -482,18 +747,50 @@ def create( ), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -501,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. @@ -512,8 +809,37 @@ 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( { "UniqueName": unique_name, @@ -526,17 +852,83 @@ async def create_async( ), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -587,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, @@ -606,6 +1048,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -632,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( @@ -640,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, @@ -664,8 +1158,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SessionPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -691,10 +1191,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SessionPage(self._version, response, self._solution) + 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: """ @@ -706,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: """ @@ -718,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 145da3a703..abf834776c 100644 --- a/twilio/rest/proxy/v1/service/session/interaction.py +++ b/twilio/rest/proxy/v1/service/session/interaction.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class InteractionInstance(InstanceResource): + class ResourceStatus(object): ACCEPTED = "accepted" ANSWERED = "answered" @@ -60,7 +61,7 @@ class Type(object): :ivar data: A JSON string that includes the message body of message interactions (e.g. `{\"body\": \"hello\"}`) or the call duration (when available) of a call (e.g. `{\"duration\": \"5\"}`). :ivar type: :ivar inbound_participant_sid: The SID of the inbound [Participant](https://www.twilio.com/docs/proxy/api/participant) resource. - :ivar inbound_resource_sid: The SID of the inbound resource; either the [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message. + :ivar inbound_resource_sid: The SID of the inbound resource; either the [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). :ivar inbound_resource_status: :ivar inbound_resource_type: The inbound resource type. Can be [Call](https://www.twilio.com/docs/voice/api/call-resource) or [Message](https://www.twilio.com/docs/sms/api/message-resource). :ivar inbound_resource_url: The URL of the Twilio inbound resource @@ -94,9 +95,9 @@ def __init__( "inbound_participant_sid" ) self.inbound_resource_sid: Optional[str] = payload.get("inbound_resource_sid") - self.inbound_resource_status: Optional[ - "InteractionInstance.ResourceStatus" - ] = payload.get("inbound_resource_status") + self.inbound_resource_status: Optional["InteractionInstance.ResourceStatus"] = ( + payload.get("inbound_resource_status") + ) self.inbound_resource_type: Optional[str] = payload.get("inbound_resource_type") self.inbound_resource_url: Optional[str] = payload.get("inbound_resource_url") self.outbound_participant_sid: Optional[str] = payload.get( @@ -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 @@ -189,6 +227,7 @@ def __repr__(self) -> str: class InteractionContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): """ Initialize the InteractionContext @@ -212,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 @@ -219,9 +272,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -231,9 +306,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the InteractionInstance 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) -> InteractionInstance: @@ -243,19 +342,47 @@ def fetch(self) -> InteractionInstance: :returns: The fetched InteractionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], ) - return InteractionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the InteractionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> InteractionInstance: """ @@ -264,19 +391,31 @@ async def fetch_async(self) -> InteractionInstance: :returns: The fetched InteractionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return InteractionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], ) - return InteractionInstance( + 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: """ @@ -289,12 +428,14 @@ def __repr__(self) -> str: class InteractionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> InteractionInstance: """ Build an instance of InteractionInstance :param payload: Payload response from the API """ + return InteractionInstance( self._version, payload, @@ -312,6 +453,7 @@ def __repr__(self) -> str: class InteractionList(ListResource): + def __init__(self, version: Version, service_sid: str, session_sid: str): """ Initialize the InteractionList @@ -384,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, @@ -403,6 +595,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -429,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( @@ -437,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, @@ -461,8 +705,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return InteractionPage(self._version, response, self._solution) + 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 InteractionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -488,10 +738,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return InteractionPage(self._version, response, self._solution) + 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: """ @@ -503,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: """ @@ -515,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 ce3c16abd0..90c3af7080 100644 --- a/twilio/rest/proxy/v1/service/session/participant/__init__.py +++ b/twilio/rest/proxy/v1/service/session/participant/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class ParticipantInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Participant resource. :ivar session_sid: The SID of the parent [Session](https://www.twilio.com/docs/proxy/api/session) resource. @@ -79,6 +78,7 @@ def __init__( "session_sid": session_sid, "sid": sid or self.sid, } + self._context: Optional[ParticipantContext] = None @property @@ -116,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 @@ -134,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: """ @@ -152,6 +188,7 @@ def __repr__(self) -> str: class ParticipantContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, session_sid: str, sid: str): """ Initialize the ParticipantContext @@ -177,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 @@ -184,9 +235,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -196,9 +269,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ParticipantInstance 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) -> ParticipantInstance: @@ -208,19 +305,47 @@ def fetch(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], ) - return ParticipantInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ParticipantInstance: """ @@ -229,19 +354,31 @@ async def fetch_async(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + session_sid=self._solution["session_sid"], + sid=self._solution["sid"], ) - return ParticipantInstance( + 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: @@ -268,12 +405,14 @@ def __repr__(self) -> str: class ParticipantPage(Page): + 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, @@ -291,6 +430,7 @@ def __repr__(self) -> str: class ParticipantList(ListResource): + def __init__(self, version: Version, service_sid: str, session_sid: str): """ Initialize the ParticipantList @@ -313,23 +453,20 @@ 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 - - :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. + Internal helper for create operation - :returns: The created ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Identifier": identifier, @@ -338,13 +475,39 @@ def create( "ProxyIdentifierSid": proxy_identifier_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -352,23 +515,51 @@ 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( { "Identifier": identifier, @@ -377,13 +568,39 @@ async def create_async( "ProxyIdentifierSid": proxy_identifier_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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: 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, @@ -391,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, @@ -441,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, @@ -460,6 +758,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -486,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( @@ -494,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, @@ -518,8 +868,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ParticipantPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -545,10 +901,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ParticipantPage(self._version, response, self._solution) + 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: """ @@ -560,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: """ @@ -572,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 b07b1782fa..49a2c998c4 100644 --- a/twilio/rest/proxy/v1/service/session/participant/message_interaction.py +++ b/twilio/rest/proxy/v1/service/session/participant/message_interaction.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class MessageInteractionInstance(InstanceResource): + class ResourceStatus(object): ACCEPTED = "accepted" ANSWERED = "answered" @@ -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 @@ -176,6 +196,7 @@ def __repr__(self) -> str: class MessageInteractionContext(InstanceContext): + def __init__( self, version: Version, @@ -206,6 +227,22 @@ def __init__( **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) -> MessageInteractionInstance: """ Fetch the MessageInteractionInstance @@ -213,13 +250,25 @@ def fetch(self) -> MessageInteractionInstance: :returns: The fetched MessageInteractionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return 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 MessageInteractionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessageInteractionInstance and return response metadata + + + :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"], @@ -227,6 +276,23 @@ def fetch(self) -> MessageInteractionInstance: 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MessageInteractionInstance: """ @@ -235,13 +301,25 @@ async def fetch_async(self) -> MessageInteractionInstance: :returns: The fetched MessageInteractionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return 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 MessageInteractionInstance( + 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"], @@ -249,6 +327,7 @@ async def fetch_async(self) -> MessageInteractionInstance: participant_sid=self._solution["participant_sid"], sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) def __repr__(self) -> str: """ @@ -261,12 +340,14 @@ def __repr__(self) -> str: class MessageInteractionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MessageInteractionInstance: """ Build an instance of MessageInteractionInstance :param payload: Payload response from the API """ + return MessageInteractionInstance( self._version, payload, @@ -285,6 +366,7 @@ def __repr__(self) -> str: class MessageInteractionList(ListResource): + def __init__( self, version: Version, service_sid: str, session_sid: str, participant_sid: str ): @@ -309,32 +391,48 @@ 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( { "Body": body, "MediaUrl": serialize.map(media_url, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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[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, @@ -343,32 +441,71 @@ 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( { "Body": body, "MediaUrl": serialize.map(media_url, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -377,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, @@ -427,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, @@ -446,6 +658,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -472,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( @@ -480,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, @@ -504,8 +768,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MessageInteractionPage(self._version, response, self._solution) + 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 MessageInteractionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -531,10 +801,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return MessageInteractionPage(self._version, response, self._solution) + 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: """ @@ -546,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: """ @@ -558,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 27dc8467f1..0000000000 --- a/twilio/rest/proxy/v1/service/short_code.py +++ /dev/null @@ -1,605 +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, 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 "".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 - """ - return self._version.delete( - method="DELETE", - uri=self._uri, - ) - - async def delete_async(self) -> bool: - """ - Asynchronous coroutine that deletes the ShortCodeInstance - - - :returns: True if delete succeeds, False otherwise - """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) - - def fetch(self) -> ShortCodeInstance: - """ - Fetch the ShortCodeInstance - - - :returns: The fetched ShortCodeInstance - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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": is_reserved, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) - - 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": is_reserved, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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 "".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 "" - - -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/docs/sms/api/short-code) resource that represents the short code you would like to assign to your Proxy Service. - - :returns: The created ShortCodeInstance - """ - data = values.of( - { - "Sid": sid, - } - ) - - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) - - 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/docs/sms/api/short-code) resource that represents the short code you would like to assign to your Proxy Service. - - :returns: The created ShortCodeInstance - """ - data = values.of( - { - "Sid": sid, - } - ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) - - 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, - } - ) - - response = self._version.page(method="GET", uri=self._uri, params=data) - 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, - } - ) - - response = await self._version.page_async( - method="GET", uri=self._uri, params=data - ) - 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 "" diff --git a/twilio/rest/routes/RoutesBase.py b/twilio/rest/routes/RoutesBase.py index 86a85dd3da..a47d67f093 100644 --- a/twilio/rest/routes/RoutesBase.py +++ b/twilio/rest/routes/RoutesBase.py @@ -17,6 +17,7 @@ class RoutesBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Routes Domain diff --git a/twilio/rest/routes/v2/__init__.py b/twilio/rest/routes/v2/__init__.py index b3852c1a6d..56a140efc3 100644 --- a/twilio/rest/routes/v2/__init__.py +++ b/twilio/rest/routes/v2/__init__.py @@ -21,6 +21,7 @@ class V2(Version): + def __init__(self, domain: Domain): """ Initialize the V2 version of Routes diff --git a/twilio/rest/routes/v2/phone_number.py b/twilio/rest/routes/v2/phone_number.py index 496a3de2ba..56b49fed77 100644 --- a/twilio/rest/routes/v2/phone_number.py +++ b/twilio/rest/routes/v2/phone_number.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class PhoneNumberInstance(InstanceResource): - """ :ivar phone_number: The phone number in E.164 format :ivar url: The absolute URL of the resource. @@ -59,6 +58,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[PhoneNumberContext] = None @property @@ -94,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, @@ -130,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 @@ -141,6 +195,7 @@ def __repr__(self) -> str: class PhoneNumberContext(InstanceContext): + def __init__(self, version: Version, phone_number: str): """ Initialize the PhoneNumberContext @@ -156,6 +211,22 @@ def __init__(self, version: Version, phone_number: str): } 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 @@ -163,17 +234,43 @@ def fetch(self) -> PhoneNumberInstance: :returns: The fetched PhoneNumberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], ) - return PhoneNumberInstance( + 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: """ @@ -182,17 +279,55 @@ async def fetch_async(self) -> PhoneNumberInstance: :returns: The fetched PhoneNumberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return PhoneNumberInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], ) - return PhoneNumberInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "VoiceRegion": voice_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, @@ -207,21 +342,60 @@ def update( :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"] + ) + + def update_with_http_info( + self, + voice_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 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, 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( { "VoiceRegion": voice_region, "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return PhoneNumberInstance( - self._version, payload, phone_number=self._solution["phone_number"] + 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( @@ -237,22 +411,33 @@ async def update_async( :returns: The updated PhoneNumberInstance """ - data = values.of( - { - "VoiceRegion": voice_region, - "FriendlyName": friendly_name, - } + payload, _, _ = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return PhoneNumberInstance( + self._version, payload, phone_number=self._solution["phone_number"] ) - return PhoneNumberInstance( + 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: """ @@ -265,6 +450,7 @@ def __repr__(self) -> str: class PhoneNumberList(ListResource): + def __init__(self, version: Version): """ Initialize the PhoneNumberList diff --git a/twilio/rest/routes/v2/sip_domain.py b/twilio/rest/routes/v2/sip_domain.py index 42755a43fc..dd4445f3b6 100644 --- a/twilio/rest/routes/v2/sip_domain.py +++ b/twilio/rest/routes/v2/sip_domain.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class SipDomainInstance(InstanceResource): - """ :ivar sip_domain: :ivar url: @@ -59,6 +58,7 @@ def __init__( self._solution = { "sip_domain": sip_domain or self.sip_domain, } + self._context: Optional[SipDomainContext] = None @property @@ -94,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, @@ -130,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 @@ -141,6 +195,7 @@ def __repr__(self) -> str: class SipDomainContext(InstanceContext): + def __init__(self, version: Version, sip_domain: str): """ Initialize the SipDomainContext @@ -156,6 +211,22 @@ def __init__(self, version: Version, sip_domain: str): } self._uri = "/SipDomains/{sip_domain}".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) -> SipDomainInstance: """ Fetch the SipDomainInstance @@ -163,17 +234,43 @@ def fetch(self) -> SipDomainInstance: :returns: The fetched SipDomainInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], ) - return SipDomainInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SipDomainInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SipDomainInstance: """ @@ -182,17 +279,55 @@ async def fetch_async(self) -> SipDomainInstance: :returns: The fetched SipDomainInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SipDomainInstance( + self._version, + payload, + sip_domain=self._solution["sip_domain"], ) - return SipDomainInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "VoiceRegion": voice_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, @@ -207,21 +342,60 @@ def update( :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"] + ) + + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + 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 = 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( { "VoiceRegion": voice_region, "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SipDomainInstance( - self._version, payload, sip_domain=self._solution["sip_domain"] + 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( @@ -237,22 +411,33 @@ async def update_async( :returns: The updated SipDomainInstance """ - data = values.of( - { - "VoiceRegion": voice_region, - "FriendlyName": friendly_name, - } + payload, _, _ = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return SipDomainInstance( + self._version, payload, sip_domain=self._solution["sip_domain"] ) - return SipDomainInstance( + 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: """ @@ -265,6 +450,7 @@ def __repr__(self) -> str: class SipDomainList(ListResource): + def __init__(self, version: Version): """ Initialize the SipDomainList diff --git a/twilio/rest/routes/v2/trunk.py b/twilio/rest/routes/v2/trunk.py index cf02b000b1..72d14c90bc 100644 --- a/twilio/rest/routes/v2/trunk.py +++ b/twilio/rest/routes/v2/trunk.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class TrunkInstance(InstanceResource): - """ :ivar sip_trunk_domain: The absolute URL of the SIP Trunk :ivar url: The absolute URL of the resource. @@ -59,6 +58,7 @@ def __init__( self._solution = { "sip_trunk_domain": sip_trunk_domain or self.sip_trunk_domain, } + self._context: Optional[TrunkContext] = None @property @@ -94,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, @@ -130,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 @@ -141,6 +195,7 @@ def __repr__(self) -> str: class TrunkContext(InstanceContext): + def __init__(self, version: Version, sip_trunk_domain: str): """ Initialize the TrunkContext @@ -156,6 +211,22 @@ def __init__(self, version: Version, sip_trunk_domain: str): } self._uri = "/Trunks/{sip_trunk_domain}".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) -> TrunkInstance: """ Fetch the TrunkInstance @@ -163,17 +234,43 @@ def fetch(self) -> TrunkInstance: :returns: The fetched TrunkInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], ) - return TrunkInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrunkInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TrunkInstance: """ @@ -182,17 +279,55 @@ async def fetch_async(self) -> TrunkInstance: :returns: The fetched TrunkInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TrunkInstance( + self._version, + payload, + sip_trunk_domain=self._solution["sip_trunk_domain"], ) - return TrunkInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "VoiceRegion": voice_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, @@ -207,21 +342,60 @@ def update( :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"] + ) + + def update_with_http_info( + self, + voice_region: Union[str, object] = values.unset, + friendly_name: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + 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 = 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( { "VoiceRegion": voice_region, "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return TrunkInstance( - self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] + 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( @@ -237,22 +411,33 @@ async def update_async( :returns: The updated TrunkInstance """ - data = values.of( - { - "VoiceRegion": voice_region, - "FriendlyName": friendly_name, - } + payload, _, _ = await self._update_async( + voice_region=voice_region, friendly_name=friendly_name ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return TrunkInstance( + self._version, payload, sip_trunk_domain=self._solution["sip_trunk_domain"] ) - return TrunkInstance( + 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: """ @@ -265,6 +450,7 @@ def __repr__(self) -> str: class TrunkList(ListResource): + def __init__(self, version: Version): """ Initialize the TrunkList diff --git a/twilio/rest/serverless/ServerlessBase.py b/twilio/rest/serverless/ServerlessBase.py index 803c63dece..d6e227c0b7 100644 --- a/twilio/rest/serverless/ServerlessBase.py +++ b/twilio/rest/serverless/ServerlessBase.py @@ -17,6 +17,7 @@ class ServerlessBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Serverless Domain diff --git a/twilio/rest/serverless/v1/__init__.py b/twilio/rest/serverless/v1/__init__.py index ea6b4e9db2..e494615caf 100644 --- a/twilio/rest/serverless/v1/__init__.py +++ b/twilio/rest/serverless/v1/__init__.py @@ -19,6 +19,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Serverless diff --git a/twilio/rest/serverless/v1/service/__init__.py b/twilio/rest/serverless/v1/service/__init__.py index 146827d812..2210d07e2e 100644 --- a/twilio/rest/serverless/v1/service/__init__.py +++ b/twilio/rest/serverless/v1/service/__init__.py @@ -12,10 +12,10 @@ 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 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,7 +28,6 @@ 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. @@ -67,6 +66,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -102,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 @@ -120,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, @@ -162,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: """ @@ -201,6 +279,7 @@ def __repr__(self) -> str: class ServiceContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ServiceContext @@ -221,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 @@ -228,9 +321,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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: @@ -240,9 +355,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -252,17 +391,43 @@ def fetch(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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: """ @@ -271,17 +436,57 @@ async def fetch_async(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "FriendlyName": friendly_name, + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + 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, @@ -298,21 +503,65 @@ def update( :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( { - "IncludeCredentials": include_credentials, + "IncludeCredentials": serialize.boolean_to_string(include_credentials), "FriendlyName": friendly_name, - "UiEditable": ui_editable, + "UiEditable": serialize.boolean_to_string(ui_editable), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -329,21 +578,35 @@ async def update_async( :returns: The updated ServiceInstance """ - data = values.of( - { - "IncludeCredentials": include_credentials, - "FriendlyName": friendly_name, - "UiEditable": ui_editable, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -404,12 +667,14 @@ def __repr__(self) -> str: 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: @@ -422,6 +687,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -433,6 +699,38 @@ def __init__(self, version: Version): self._uri = "/Services" + def _create( + self, + unique_name: str, + friendly_name: str, + include_credentials: Union[bool, object] = values.unset, + ui_editable: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "FriendlyName": friendly_name, + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "UiEditable": serialize.boolean_to_string(ui_editable), + } + ) + 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, unique_name: str, @@ -450,22 +748,71 @@ def create( :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( { "UniqueName": unique_name, "FriendlyName": friendly_name, - "IncludeCredentials": include_credentials, - "UiEditable": ui_editable, + "IncludeCredentials": serialize.boolean_to_string(include_credentials), + "UiEditable": serialize.boolean_to_string(ui_editable), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(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, @@ -484,22 +831,39 @@ async def create_async( :returns: The created ServiceInstance """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - "IncludeCredentials": include_credentials, - "UiEditable": ui_editable, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return ServiceInstance(self._version, payload) + :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, @@ -551,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, @@ -570,6 +984,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -596,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( @@ -604,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, @@ -628,7 +1094,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -655,11 +1127,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 7b70adf1c4..8eae827c10 100644 --- a/twilio/rest/serverless/v1/service/asset/__init__.py +++ b/twilio/rest/serverless/v1/service/asset/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class AssetInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Asset resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Asset resource. @@ -63,6 +62,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[AssetContext] = None @property @@ -99,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 @@ -117,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 @@ -141,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: """ @@ -159,6 +219,7 @@ def __repr__(self) -> str: class AssetContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the AssetContext @@ -178,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 @@ -185,9 +260,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -197,9 +294,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the AssetInstance 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) -> AssetInstance: @@ -209,18 +330,45 @@ def fetch(self) -> AssetInstance: :returns: The fetched AssetInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AssetInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return AssetInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssetInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AssetInstance: """ @@ -229,12 +377,7 @@ async def fetch_async(self) -> AssetInstance: :returns: The fetched AssetInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return AssetInstance( self._version, payload, @@ -242,26 +385,54 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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: 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, @@ -269,26 +440,55 @@ 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( { "FriendlyName": friendly_name, } ) + 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, + 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, @@ -296,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: """ @@ -320,12 +539,14 @@ def __repr__(self) -> str: class AssetPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AssetInstance: """ Build an instance of AssetInstance :param payload: Payload response from the API """ + return AssetInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -340,6 +561,7 @@ def __repr__(self) -> str: class AssetList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the AssetList @@ -356,54 +578,108 @@ 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 + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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) -> 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( { "FriendlyName": friendly_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, + 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, @@ -454,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, @@ -473,6 +799,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -499,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( @@ -507,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, @@ -531,8 +909,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AssetPage(self._version, response, self._solution) + 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 AssetPage(self._version, response, solution=self._solution) async def page_async( self, @@ -558,10 +942,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return AssetPage(self._version, response, self._solution) + 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: """ @@ -573,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: """ @@ -585,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 34ebb07ef0..a8d50afe6b 100644 --- a/twilio/rest/serverless/v1/service/asset/asset_version.py +++ b/twilio/rest/serverless/v1/service/asset/asset_version.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class AssetVersionInstance(InstanceResource): + class Visibility(object): PUBLIC = "public" PRIVATE = "private" @@ -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 @@ -116,6 +136,7 @@ def __repr__(self) -> str: class AssetVersionContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, asset_sid: str, sid: str): """ Initialize the AssetVersionContext @@ -137,6 +158,22 @@ def __init__(self, version: Version, service_sid: str, asset_sid: str, sid: str) **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) -> AssetVersionInstance: """ Fetch the AssetVersionInstance @@ -144,19 +181,47 @@ def fetch(self) -> AssetVersionInstance: :returns: The fetched AssetVersionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], ) - return AssetVersionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AssetVersionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AssetVersionInstance: """ @@ -165,19 +230,31 @@ async def fetch_async(self) -> AssetVersionInstance: :returns: The fetched AssetVersionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AssetVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + asset_sid=self._solution["asset_sid"], + sid=self._solution["sid"], ) - return AssetVersionInstance( + 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: """ @@ -190,12 +267,14 @@ def __repr__(self) -> str: class AssetVersionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> AssetVersionInstance: """ Build an instance of AssetVersionInstance :param payload: Payload response from the API """ + return AssetVersionInstance( self._version, payload, @@ -213,6 +292,7 @@ def __repr__(self) -> str: class AssetVersionList(ListResource): + def __init__(self, version: Version, service_sid: str, asset_sid: str): """ Initialize the AssetVersionList @@ -283,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, @@ -302,6 +432,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -328,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( @@ -336,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, @@ -360,8 +542,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return AssetVersionPage(self._version, response, self._solution) + 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 AssetVersionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -387,10 +575,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return AssetVersionPage(self._version, response, self._solution) + 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: """ @@ -402,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: """ @@ -414,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 0fe3b8f923..bc54d0b495 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,14 +25,25 @@ from twilio.rest.serverless.v1.service.build.build_status import BuildStatusList + + + + + + class BuildInstance(InstanceResource): + + class Runtime(object): NODE8 = "node8" NODE10 = "node10" NODE12 = "node12" NODE14 = "node14" NODE16 = "node16" + NODE18 = "node18" + NODE20 = "node20" + NODE22 = "node22" class Status(object): BUILDING = "building" @@ -53,7 +65,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) @@ -61,9 +73,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str, self.account_sid: Optional[str] = payload.get("account_sid") self.service_sid: Optional[str] = payload.get("service_sid") self.status: Optional["BuildInstance.Status"] = payload.get("status") - self.asset_versions: Optional[List[object]] = payload.get("asset_versions") - self.function_versions: Optional[List[object]] = payload.get("function_versions") - self.dependencies: Optional[List[object]] = payload.get("dependencies") + self.asset_versions: Optional[List[Dict[str, object]]] = payload.get("asset_versions") + self.function_versions: Optional[List[Dict[str, object]]] = payload.get("function_versions") + self.dependencies: Optional[List[Dict[str, object]]] = payload.get("dependencies") self.runtime: Optional["BuildInstance.Runtime"] = payload.get("runtime") self.date_created: Optional[datetime] = deserialize.iso8601_datetime(payload.get("date_created")) self.date_updated: Optional[datetime] = deserialize.iso8601_datetime(payload.get("date_updated")) @@ -71,10 +83,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 @@ -106,6 +121,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": @@ -125,6 +158,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: @@ -144,6 +195,7 @@ def __repr__(self) -> str: class BuildContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the BuildContext @@ -165,6 +217,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 @@ -172,7 +239,32 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete(method='DELETE', uri=self._uri,) + 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 await self._version.delete_with_response_info_async(method='DELETE', uri=self._uri, headers=headers) async def delete_async(self) -> bool: """ @@ -181,9 +273,37 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async(method='DELETE', uri=self._uri,) + 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 + + + :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) -> BuildInstance: """ Fetch the BuildInstance @@ -191,16 +311,48 @@ def fetch(self) -> BuildInstance: :returns: The fetched BuildInstance """ + payload, _, _ = self._fetch() + return BuildInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BuildInstance and return response metadata - payload = self._version.fetch(method='GET', uri=self._uri, ) - return 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" + + return await self._version.fetch_with_response_info_async(method='GET', uri=self._uri, headers=headers) async def fetch_async(self) -> BuildInstance: """ @@ -209,16 +361,31 @@ async def fetch_async(self) -> BuildInstance: :returns: The fetched BuildInstance """ + payload, _, _ = await self._fetch_async() + return BuildInstance( + 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 BuildInstance and return response metadata - payload = await self._version.fetch_async(method='GET', uri=self._uri, ) - return BuildInstance( + :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 @@ -259,7 +426,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: """ @@ -274,7 +443,7 @@ def __repr__(self) -> str: class BuildList(ListResource): - + def __init__(self, version: Version, service_sid: str): """ Initialize the BuildList @@ -294,6 +463,32 @@ 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({ + 'AssetVersions': serialize.map(asset_versions, lambda e: e), + 'FunctionVersions': serialize.map(function_versions, lambda e: e), + 'Dependencies': dependencies, + 'Runtime': runtime, + }) + 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, 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 @@ -305,16 +500,49 @@ def create(self, asset_versions: Union[List[str], object]=values.unset, function :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']) + + 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: + """ + 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 = 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({ 'AssetVersions': serialize.map(asset_versions, lambda e: e), 'FunctionVersions': serialize.map(function_versions, lambda e: e), 'Dependencies': dependencies, 'Runtime': runtime, }) + headers = values.of({ + 'Content-Type': 'application/x-www-form-urlencoded' + }) - payload = self._version.create(method='POST', uri=self._uri, data=data,) - - return BuildInstance(self._version, payload, service_sid=self._solution['service_sid']) + 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, 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: """ @@ -327,16 +555,23 @@ async def create_async(self, asset_versions: Union[List[str], object]=values.uns :returns: The created BuildInstance """ - data = values.of({ - 'AssetVersions': serialize.map(asset_versions, lambda e: e), - 'FunctionVersions': serialize.map(function_versions, lambda e: e), - 'Dependencies': dependencies, - 'Runtime': runtime, - }) - - payload = await self._version.create_async(method='POST', uri=self._uri, data=data,) - + 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, @@ -393,6 +628,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, @@ -409,9 +696,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, @@ -433,16 +721,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, @@ -463,11 +803,19 @@ def page(self, 'PageSize': page_size, }) - response = self._version.page(method='GET', uri=self._uri, params=data) - return BuildPage(self._version, response, self._solution) + 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 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, @@ -488,8 +836,84 @@ async def page_async(self, 'PageSize': page_size, }) - response = await self._version.page_async(method='GET', uri=self._uri, params=data) - return BuildPage(self._version, response, self._solution) + 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 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: """ @@ -504,7 +928,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: """ @@ -519,7 +943,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) @@ -549,3 +973,4 @@ def __repr__(self) -> str: """ return '' + diff --git a/twilio/rest/serverless/v1/service/build/build_status.py b/twilio/rest/serverless/v1/service/build/build_status.py index c127f89a4f..03a81818c1 100644 --- a/twilio/rest/serverless/v1/service/build/build_status.py +++ b/twilio/rest/serverless/v1/service/build/build_status.py @@ -14,6 +14,8 @@ 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 @@ -21,8 +23,16 @@ + + + + + + class BuildStatusInstance(InstanceResource): + + class Status(object): BUILDING = "building" COMPLETED = "completed" @@ -36,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) @@ -47,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 @@ -83,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: """ @@ -95,6 +126,7 @@ def __repr__(self) -> str: class BuildStatusContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the BuildStatusContext @@ -115,6 +147,23 @@ def __init__(self, version: Version, service_sid: str, sid: str): + 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) -> BuildStatusInstance: """ Fetch the BuildStatusInstance @@ -122,16 +171,48 @@ def fetch(self) -> BuildStatusInstance: :returns: The fetched BuildStatusInstance """ + payload, _, _ = self._fetch() + return BuildStatusInstance( + self._version, + payload, + service_sid=self._solution['service_sid'], + sid=self._solution['sid'], + + ) + + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the BuildStatusInstance and return response metadata - payload = self._version.fetch(method='GET', uri=self._uri, ) - return 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" + + return await self._version.fetch_with_response_info_async(method='GET', uri=self._uri, headers=headers) async def fetch_async(self) -> BuildStatusInstance: """ @@ -140,16 +221,31 @@ async def fetch_async(self) -> BuildStatusInstance: :returns: The fetched BuildStatusInstance """ + payload, _, _ = await self._fetch_async() + return BuildStatusInstance( + 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 BuildStatusInstance and return response metadata - payload = await self._version.fetch_async(method='GET', uri=self._uri, ) - return BuildStatusInstance( + :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: @@ -164,7 +260,7 @@ def __repr__(self) -> str: class BuildStatusList(ListResource): - + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the BuildStatusList @@ -205,3 +301,4 @@ def __repr__(self) -> str: """ return '' + diff --git a/twilio/rest/serverless/v1/service/environment/__init__.py b/twilio/rest/serverless/v1/service/environment/__init__.py index dac46b9744..f5817a338c 100644 --- a/twilio/rest/serverless/v1/service/environment/__init__.py +++ b/twilio/rest/serverless/v1/service/environment/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class EnvironmentInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Environment resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Environment resource. @@ -71,6 +70,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[EnvironmentContext] = None @property @@ -107,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 @@ -125,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: """ @@ -157,6 +193,7 @@ def __repr__(self) -> str: class EnvironmentContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the EnvironmentContext @@ -180,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 @@ -187,9 +238,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -199,9 +272,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EnvironmentInstance 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) -> EnvironmentInstance: @@ -211,18 +308,45 @@ def fetch(self) -> EnvironmentInstance: :returns: The fetched EnvironmentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return EnvironmentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EnvironmentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EnvironmentInstance: """ @@ -231,18 +355,29 @@ async def fetch_async(self) -> EnvironmentInstance: :returns: The fetched EnvironmentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EnvironmentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return EnvironmentInstance( + 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: @@ -294,12 +429,14 @@ def __repr__(self) -> str: class EnvironmentPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EnvironmentInstance: """ Build an instance of EnvironmentInstance :param payload: Payload response from the API """ + return EnvironmentInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -314,6 +451,7 @@ def __repr__(self) -> str: class EnvironmentList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the EnvironmentList @@ -330,6 +468,32 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Environments".format(**self._solution) + def _create( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "DomainSuffix": domain_suffix, + } + ) + 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, unique_name: str, domain_suffix: Union[str, object] = values.unset ) -> EnvironmentInstance: @@ -341,21 +505,56 @@ def create( :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"] + ) + + def create_with_http_info( + self, unique_name: str, domain_suffix: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "UniqueName": unique_name, "DomainSuffix": domain_suffix, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return EnvironmentInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -369,22 +568,31 @@ async def create_async( :returns: The created EnvironmentInstance """ - data = values.of( - { - "UniqueName": unique_name, - "DomainSuffix": domain_suffix, - } + payload, _, _ = await self._create_async( + unique_name=unique_name, domain_suffix=domain_suffix ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return EnvironmentInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return EnvironmentInstance( + 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, @@ -436,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, @@ -455,6 +713,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -481,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( @@ -489,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, @@ -513,8 +823,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return EnvironmentPage(self._version, response, self._solution) + 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 EnvironmentPage(self._version, response, solution=self._solution) async def page_async( self, @@ -540,10 +856,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return EnvironmentPage(self._version, response, self._solution) + 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: """ @@ -555,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: """ @@ -567,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 f0f6b50037..65fecb891a 100644 --- a/twilio/rest/serverless/v1/service/environment/deployment.py +++ b/twilio/rest/serverless/v1/service/environment/deployment.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class DeploymentInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Deployment resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Deployment resource. @@ -64,6 +63,7 @@ def __init__( "environment_sid": environment_sid, "sid": sid or self.sid, } + self._context: Optional[DeploymentContext] = None @property @@ -101,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 @@ -112,6 +130,7 @@ def __repr__(self) -> str: class DeploymentContext(InstanceContext): + def __init__( self, version: Version, service_sid: str, environment_sid: str, sid: str ): @@ -135,6 +154,22 @@ def __init__( **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) -> DeploymentInstance: """ Fetch the DeploymentInstance @@ -142,19 +177,47 @@ def fetch(self) -> DeploymentInstance: :returns: The fetched DeploymentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - return DeploymentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DeploymentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> DeploymentInstance: """ @@ -163,19 +226,31 @@ async def fetch_async(self) -> DeploymentInstance: :returns: The fetched DeploymentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return DeploymentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - return DeploymentInstance( + 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: """ @@ -188,12 +263,14 @@ def __repr__(self) -> str: class DeploymentPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> DeploymentInstance: """ Build an instance of DeploymentInstance :param payload: Payload response from the API """ + return DeploymentInstance( self._version, payload, @@ -211,6 +288,7 @@ def __repr__(self) -> str: class DeploymentList(ListResource): + def __init__(self, version: Version, service_sid: str, environment_sid: str): """ Initialize the DeploymentList @@ -233,28 +311,48 @@ def __init__(self, version: Version, service_sid: str, environment_sid: str): ) ) - def create( - self, build_sid: Union[str, object] = values.unset - ) -> DeploymentInstance: + def _create( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> tuple: """ - Create the DeploymentInstance + Internal helper for create operation - :param build_sid: The SID of the Build for the Deployment. - - :returns: The created DeploymentInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "BuildSid": build_sid, + "IsPlugin": serialize.boolean_to_string(is_plugin), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -262,28 +360,74 @@ def create( environment_sid=self._solution["environment_sid"], ) - async def create_async( - self, build_sid: Union[str, object] = values.unset - ) -> DeploymentInstance: + def create_with_http_info( + self, + build_sid: Union[str, object] = values.unset, + is_plugin: Union[bool, object] = values.unset, + ) -> 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( { "BuildSid": build_sid, + "IsPlugin": serialize.boolean_to_string(is_plugin), } ) + 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, + 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, @@ -291,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, @@ -341,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, @@ -360,6 +578,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -386,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( @@ -394,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, @@ -418,8 +688,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DeploymentPage(self._version, response, self._solution) + 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 DeploymentPage(self._version, response, solution=self._solution) async def page_async( self, @@ -445,10 +721,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return DeploymentPage(self._version, response, self._solution) + 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: """ @@ -460,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: """ @@ -472,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 d856ba75d8..30ff705ac5 100644 --- a/twilio/rest/serverless/v1/service/environment/log.py +++ b/twilio/rest/serverless/v1/service/environment/log.py @@ -12,10 +12,10 @@ 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 @@ -24,11 +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 @@ -122,6 +136,7 @@ def __repr__(self) -> str: class LogContext(InstanceContext): + def __init__( self, version: Version, service_sid: str, environment_sid: str, sid: str ): @@ -147,6 +162,22 @@ def __init__( ) ) + 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) -> LogInstance: """ Fetch the LogInstance @@ -154,19 +185,47 @@ def fetch(self) -> LogInstance: :returns: The fetched LogInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - return LogInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the LogInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> LogInstance: """ @@ -175,19 +234,31 @@ async def fetch_async(self) -> LogInstance: :returns: The fetched LogInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return LogInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - return LogInstance( + 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: """ @@ -200,12 +271,14 @@ def __repr__(self) -> str: class LogPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> LogInstance: """ Build an instance of LogInstance :param payload: Payload response from the API """ + return LogInstance( self._version, payload, @@ -223,6 +296,7 @@ def __repr__(self) -> str: class LogList(ListResource): + def __init__(self, version: Version, service_sid: str, environment_sid: str): """ Initialize the LogList @@ -317,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, @@ -342,6 +486,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( function_sid=function_sid, @@ -377,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( @@ -388,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, @@ -421,8 +635,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return LogPage(self._version, response, self._solution) + 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 LogPage(self._version, response, solution=self._solution) async def page_async( self, @@ -457,10 +677,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return LogPage(self._version, response, self._solution) + 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: """ @@ -472,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: """ @@ -484,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 b619e3a655..13597a5419 100644 --- a/twilio/rest/serverless/v1/service/environment/variable.py +++ b/twilio/rest/serverless/v1/service/environment/variable.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class VariableInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Variable resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Variable resource. @@ -66,6 +65,7 @@ def __init__( "environment_sid": environment_sid, "sid": sid or self.sid, } + self._context: Optional[VariableContext] = None @property @@ -103,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 @@ -121,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, @@ -157,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 @@ -168,6 +240,7 @@ def __repr__(self) -> str: class VariableContext(InstanceContext): + def __init__( self, version: Version, service_sid: str, environment_sid: str, sid: str ): @@ -191,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 @@ -198,9 +285,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -210,9 +319,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the VariableInstance 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) -> VariableInstance: @@ -222,19 +355,47 @@ def fetch(self) -> VariableInstance: :returns: The fetched VariableInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - return VariableInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VariableInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> VariableInstance: """ @@ -243,46 +404,74 @@ async def fetch_async(self) -> VariableInstance: :returns: The fetched VariableInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return VariableInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + environment_sid=self._solution["environment_sid"], + sid=self._solution["sid"], ) - return VariableInstance( + 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( + def _update( self, key: Union[str, object] = values.unset, value: Union[str, object] = values.unset, - ) -> VariableInstance: + ) -> tuple: """ - 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. + Internal helper for update operation - :returns: The updated VariableInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Key": key, "Value": value, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -291,32 +480,71 @@ 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( { "Key": key, "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, + 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, @@ -325,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 @@ -336,12 +587,14 @@ def __repr__(self) -> str: class VariablePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> VariableInstance: """ Build an instance of VariableInstance :param payload: Payload response from the API """ + return VariableInstance( self._version, payload, @@ -359,6 +612,7 @@ def __repr__(self) -> str: class VariableList(ListResource): + def __init__(self, version: Version, service_sid: str, environment_sid: str): """ Initialize the VariableList @@ -381,28 +635,40 @@ 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 - - :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. + Internal helper for create operation - :returns: The created VariableInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Key": key, "Value": value, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -410,28 +676,58 @@ 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( { "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, + 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, @@ -439,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, @@ -489,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, @@ -508,6 +872,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -534,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( @@ -542,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, @@ -566,8 +982,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return VariablePage(self._version, response, self._solution) + 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 VariablePage(self._version, response, solution=self._solution) async def page_async( self, @@ -593,10 +1015,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return VariablePage(self._version, response, self._solution) + 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: """ @@ -608,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: """ @@ -620,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 3f2919316d..31c142d1f8 100644 --- a/twilio/rest/serverless/v1/service/function/__init__.py +++ b/twilio/rest/serverless/v1/service/function/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class FunctionInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Function resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function resource. @@ -65,6 +64,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[FunctionContext] = None @property @@ -101,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 @@ -119,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 @@ -143,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: """ @@ -161,6 +221,7 @@ def __repr__(self) -> str: class FunctionContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the FunctionContext @@ -180,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 @@ -187,9 +262,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -199,9 +296,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FunctionInstance 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) -> FunctionInstance: @@ -211,18 +332,45 @@ def fetch(self) -> FunctionInstance: :returns: The fetched FunctionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FunctionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return FunctionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FunctionInstance: """ @@ -231,12 +379,7 @@ async def fetch_async(self) -> FunctionInstance: :returns: The fetched FunctionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return FunctionInstance( self._version, payload, @@ -244,26 +387,54 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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: 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, @@ -271,26 +442,55 @@ 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( { "FriendlyName": friendly_name, } ) + 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, + 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, @@ -298,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: """ @@ -322,12 +541,14 @@ def __repr__(self) -> str: class FunctionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> FunctionInstance: """ Build an instance of FunctionInstance :param payload: Payload response from the API """ + return FunctionInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -342,6 +563,7 @@ def __repr__(self) -> str: class FunctionList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the FunctionList @@ -358,54 +580,108 @@ 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 + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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) -> 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( { "FriendlyName": friendly_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, + 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, @@ -456,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, @@ -475,6 +801,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -501,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( @@ -509,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, @@ -533,8 +911,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return FunctionPage(self._version, response, self._solution) + 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 FunctionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -560,10 +944,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return FunctionPage(self._version, response, self._solution) + 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: """ @@ -575,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: """ @@ -587,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 73443897a9..75cdb11b4f 100644 --- a/twilio/rest/serverless/v1/service/function/function_version/__init__.py +++ b/twilio/rest/serverless/v1/service/function/function_version/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,6 +27,7 @@ class FunctionVersionInstance(InstanceResource): + class Visibility(object): PUBLIC = "public" PRIVATE = "private" @@ -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: """ @@ -128,6 +148,7 @@ def __repr__(self) -> str: class FunctionVersionContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): """ Initialize the FunctionVersionContext @@ -153,6 +174,22 @@ def __init__(self, version: Version, service_sid: str, function_sid: str, sid: s self._function_version_content: Optional[FunctionVersionContentList] = None + 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) -> FunctionVersionInstance: """ Fetch the FunctionVersionInstance @@ -160,19 +197,47 @@ def fetch(self) -> FunctionVersionInstance: :returns: The fetched FunctionVersionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], ) - return FunctionVersionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionVersionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FunctionVersionInstance: """ @@ -181,19 +246,31 @@ async def fetch_async(self) -> FunctionVersionInstance: :returns: The fetched FunctionVersionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return FunctionVersionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], ) - return FunctionVersionInstance( + 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: @@ -220,12 +297,14 @@ def __repr__(self) -> str: class FunctionVersionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> FunctionVersionInstance: """ Build an instance of FunctionVersionInstance :param payload: Payload response from the API """ + return FunctionVersionInstance( self._version, payload, @@ -243,6 +322,7 @@ def __repr__(self) -> str: class FunctionVersionList(ListResource): + def __init__(self, version: Version, service_sid: str, function_sid: str): """ Initialize the FunctionVersionList @@ -313,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, @@ -332,6 +462,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -358,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( @@ -366,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, @@ -390,8 +572,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return FunctionVersionPage(self._version, response, self._solution) + 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 FunctionVersionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -417,10 +605,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return FunctionVersionPage(self._version, response, self._solution) + 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: """ @@ -432,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: """ @@ -444,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 c39f9f0710..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 @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class FunctionVersionContentInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Function Version resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Function Version resource. @@ -53,6 +53,7 @@ def __init__( "function_sid": function_sid, "sid": sid, } + self._context: Optional[FunctionVersionContentContext] = None @property @@ -90,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 @@ -103,6 +122,7 @@ def __repr__(self) -> str: class FunctionVersionContentContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): """ Initialize the FunctionVersionContentContext @@ -124,6 +144,22 @@ def __init__(self, version: Version, service_sid: str, function_sid: str, sid: s **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) -> FunctionVersionContentInstance: """ Fetch the FunctionVersionContentInstance @@ -131,19 +167,47 @@ def fetch(self) -> FunctionVersionContentInstance: :returns: The fetched FunctionVersionContentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], ) - return FunctionVersionContentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FunctionVersionContentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FunctionVersionContentInstance: """ @@ -152,19 +216,31 @@ async def fetch_async(self) -> FunctionVersionContentInstance: :returns: The fetched FunctionVersionContentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return FunctionVersionContentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + function_sid=self._solution["function_sid"], + sid=self._solution["sid"], ) - return FunctionVersionContentInstance( + 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: """ @@ -177,6 +253,7 @@ def __repr__(self) -> str: class FunctionVersionContentList(ListResource): + def __init__(self, version: Version, service_sid: str, function_sid: str, sid: str): """ Initialize the FunctionVersionContentList diff --git a/twilio/rest/studio/StudioBase.py b/twilio/rest/studio/StudioBase.py index e1b2374226..3b218775c8 100644 --- a/twilio/rest/studio/StudioBase.py +++ b/twilio/rest/studio/StudioBase.py @@ -18,6 +18,7 @@ class StudioBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Studio Domain diff --git a/twilio/rest/studio/v1/__init__.py b/twilio/rest/studio/v1/__init__.py index d5ca90bb68..8ab7d71b6c 100644 --- a/twilio/rest/studio/v1/__init__.py +++ b/twilio/rest/studio/v1/__init__.py @@ -19,6 +19,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Studio diff --git a/twilio/rest/studio/v1/flow/__init__.py b/twilio/rest/studio/v1/flow/__init__.py index a7c5756e04..a2795280f7 100644 --- a/twilio/rest/studio/v1/flow/__init__.py +++ b/twilio/rest/studio/v1/flow/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,6 +26,7 @@ class FlowInstance(InstanceResource): + class Status(object): DRAFT = "draft" PUBLISHED = "published" @@ -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: """ @@ -142,6 +180,7 @@ def __repr__(self) -> str: class FlowContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the FlowContext @@ -160,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 @@ -167,9 +220,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -179,9 +254,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance 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) -> FlowInstance: @@ -191,17 +290,43 @@ def fetch(self) -> FlowInstance: :returns: The fetched FlowInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FlowInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FlowInstance: """ @@ -210,17 +335,27 @@ async def fetch_async(self) -> FlowInstance: :returns: The fetched FlowInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FlowInstance( + 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: @@ -257,12 +392,14 @@ def __repr__(self) -> str: class FlowPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: """ Build an instance of FlowInstance :param payload: Payload response from the API """ + return FlowInstance(self._version, payload) def __repr__(self) -> str: @@ -275,6 +412,7 @@ def __repr__(self) -> str: class FlowList(ListResource): + def __init__(self, version: Version): """ Initialize the FlowList @@ -336,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, @@ -355,6 +543,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -381,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( @@ -389,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, @@ -413,7 +653,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 FlowPage(self._version, response) async def page_async( @@ -440,11 +686,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 e0f56dbaf7..a899206caf 100644 --- a/twilio/rest/studio/v1/flow/engagement/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/__init__.py @@ -12,10 +12,10 @@ 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 @@ -28,6 +28,7 @@ class EngagementInstance(InstanceResource): + class Status(object): ACTIVE = "active" ENDED = "ended" @@ -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: """ @@ -156,6 +194,7 @@ def __repr__(self) -> str: class EngagementContext(InstanceContext): + def __init__(self, version: Version, flow_sid: str, sid: str): """ Initialize the EngagementContext @@ -176,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 @@ -183,9 +236,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -195,9 +270,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EngagementInstance 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) -> EngagementInstance: @@ -207,18 +306,45 @@ def fetch(self) -> EngagementInstance: :returns: The fetched EngagementInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) - return EngagementInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EngagementInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EngagementInstance: """ @@ -227,18 +353,29 @@ async def fetch_async(self) -> EngagementInstance: :returns: The fetched EngagementInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EngagementInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) - return EngagementInstance( + 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: @@ -277,12 +414,14 @@ def __repr__(self) -> str: class EngagementPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EngagementInstance: """ Build an instance of EngagementInstance :param payload: Payload response from the API """ + return EngagementInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) @@ -297,6 +436,7 @@ def __repr__(self) -> str: class EngagementList(ListResource): + def __init__(self, version: Version, flow_sid: str): """ Initialize the EngagementList @@ -313,6 +453,33 @@ def __init__(self, version: Version, flow_sid: str): } self._uri = "/Flows/{flow_sid}/Engagements".format(**self._solution) + def _create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + 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, to: str, from_: str, parameters: Union[object, object] = values.unset ) -> EngagementInstance: @@ -325,6 +492,41 @@ def create( :returns: The created EngagementInstance """ + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def create_with_http_info( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "To": to, @@ -332,15 +534,14 @@ def create( "Parameters": serialize.object(parameters), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return EngagementInstance( - self._version, payload, flow_sid=self._solution["flow_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( @@ -355,23 +556,32 @@ async def create_async( :returns: The created EngagementInstance """ - data = values.of( - { - "To": to, - "From": from_, - "Parameters": serialize.object(parameters), - } + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return EngagementInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] ) - return EngagementInstance( + 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, @@ -423,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, @@ -442,6 +702,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -468,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( @@ -476,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, @@ -500,8 +812,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return EngagementPage(self._version, response, self._solution) + 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 EngagementPage(self._version, response, solution=self._solution) async def page_async( self, @@ -527,10 +845,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return EngagementPage(self._version, response, self._solution) + 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: """ @@ -542,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: """ @@ -554,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 d558b38bed..3b0cf3cf52 100644 --- a/twilio/rest/studio/v1/flow/engagement/engagement_context.py +++ b/twilio/rest/studio/v1/flow/engagement/engagement_context.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class EngagementContextInstance(InstanceResource): - """ :ivar account_sid: The SID of the Account. :ivar context: As your flow executes, we save the state in what's called the Flow Context. Any data in the flow context can be accessed by your widgets as variables, either in configuration fields or in text areas as variable substitution. @@ -49,6 +49,7 @@ def __init__( "flow_sid": flow_sid, "engagement_sid": engagement_sid, } + self._context: Optional[EngagementContextContext] = None @property @@ -85,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 @@ -96,6 +115,7 @@ def __repr__(self) -> str: class EngagementContextContext(InstanceContext): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): """ Initialize the EngagementContextContext @@ -115,6 +135,22 @@ def __init__(self, version: Version, flow_sid: str, engagement_sid: str): **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) -> EngagementContextInstance: """ Fetch the EngagementContextInstance @@ -122,18 +158,45 @@ def fetch(self) -> EngagementContextInstance: :returns: The fetched EngagementContextInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], ) - return EngagementContextInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EngagementContextInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EngagementContextInstance: """ @@ -142,18 +205,29 @@ async def fetch_async(self) -> EngagementContextInstance: :returns: The fetched EngagementContextInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EngagementContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], ) - return EngagementContextInstance( + 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: """ @@ -166,6 +240,7 @@ def __repr__(self) -> str: class EngagementContextList(ListResource): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): """ Initialize the EngagementContextList diff --git a/twilio/rest/studio/v1/flow/engagement/step/__init__.py b/twilio/rest/studio/v1/flow/engagement/step/__init__.py index c1638f29cf..25a925f124 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/__init__.py +++ b/twilio/rest/studio/v1/flow/engagement/step/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class StepInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Step resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Step resource. @@ -33,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. @@ -57,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") ) @@ -73,6 +76,7 @@ def __init__( "engagement_sid": engagement_sid, "sid": sid or self.sid, } + self._context: Optional[StepContext] = None @property @@ -110,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: """ @@ -128,6 +150,7 @@ def __repr__(self) -> str: class StepContext(InstanceContext): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str, sid: str): """ Initialize the StepContext @@ -151,6 +174,22 @@ def __init__(self, version: Version, flow_sid: str, engagement_sid: str, sid: st self._step_context: Optional[StepContextList] = None + 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) -> StepInstance: """ Fetch the StepInstance @@ -158,19 +197,47 @@ def fetch(self) -> StepInstance: :returns: The fetched StepInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], ) - return StepInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the StepInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> StepInstance: """ @@ -179,19 +246,31 @@ async def fetch_async(self) -> StepInstance: :returns: The fetched StepInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return StepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + sid=self._solution["sid"], ) - return StepInstance( + 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: @@ -218,12 +297,14 @@ def __repr__(self) -> str: class StepPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> StepInstance: """ Build an instance of StepInstance :param payload: Payload response from the API """ + return StepInstance( self._version, payload, @@ -241,6 +322,7 @@ def __repr__(self) -> str: class StepList(ListResource): + def __init__(self, version: Version, flow_sid: str, engagement_sid: str): """ Initialize the StepList @@ -311,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, @@ -330,6 +462,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -356,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( @@ -364,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, @@ -388,8 +572,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return StepPage(self._version, response, self._solution) + 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 StepPage(self._version, response, solution=self._solution) async def page_async( self, @@ -415,10 +605,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return StepPage(self._version, response, self._solution) + 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: """ @@ -430,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: """ @@ -442,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 c1555d05ab..26f82d470d 100644 --- a/twilio/rest/studio/v1/flow/engagement/step/step_context.py +++ b/twilio/rest/studio/v1/flow/engagement/step/step_context.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class StepContextInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the StepContext resource. :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. @@ -53,6 +53,7 @@ def __init__( "engagement_sid": engagement_sid, "step_sid": step_sid, } + self._context: Optional[StepContextContext] = None @property @@ -90,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 @@ -101,6 +120,7 @@ def __repr__(self) -> str: class StepContextContext(InstanceContext): + def __init__( self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str ): @@ -124,6 +144,22 @@ def __init__( **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) -> StepContextInstance: """ Fetch the StepContextInstance @@ -131,19 +167,47 @@ def fetch(self) -> StepContextInstance: :returns: The fetched StepContextInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], ) - return StepContextInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the StepContextInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> StepContextInstance: """ @@ -152,19 +216,31 @@ async def fetch_async(self) -> StepContextInstance: :returns: The fetched StepContextInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return StepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + engagement_sid=self._solution["engagement_sid"], + step_sid=self._solution["step_sid"], ) - return StepContextInstance( + 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: """ @@ -177,6 +253,7 @@ def __repr__(self) -> str: class StepContextList(ListResource): + def __init__( self, version: Version, flow_sid: str, engagement_sid: str, step_sid: str ): diff --git a/twilio/rest/studio/v1/flow/execution/__init__.py b/twilio/rest/studio/v1/flow/execution/__init__.py index d0ad05b67a..5ee77d109e 100644 --- a/twilio/rest/studio/v1/flow/execution/__init__.py +++ b/twilio/rest/studio/v1/flow/execution/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,6 +26,7 @@ class ExecutionInstance(InstanceResource): + class Status(object): ACTIVE = "active" ENDED = "ended" @@ -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: """ @@ -180,6 +244,7 @@ def __repr__(self) -> str: class ExecutionContext(InstanceContext): + def __init__(self, version: Version, flow_sid: str, sid: str): """ Initialize the ExecutionContext @@ -200,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 @@ -207,9 +286,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -219,9 +320,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance 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) -> ExecutionInstance: @@ -231,18 +356,45 @@ def fetch(self) -> ExecutionInstance: :returns: The fetched ExecutionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) - return ExecutionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExecutionInstance: """ @@ -251,12 +403,7 @@ async def fetch_async(self) -> ExecutionInstance: :returns: The fetched ExecutionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return ExecutionInstance( self._version, payload, @@ -264,26 +411,54 @@ 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( { "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -291,28 +466,57 @@ 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( { "Status": status, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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: "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, @@ -320,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: """ @@ -357,12 +580,14 @@ def __repr__(self) -> str: class ExecutionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: """ Build an instance of ExecutionInstance :param payload: Payload response from the API """ + return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) @@ -377,6 +602,7 @@ def __repr__(self) -> str: class ExecutionList(ListResource): + def __init__(self, version: Version, flow_sid: str): """ Initialize the ExecutionList @@ -393,6 +619,33 @@ def __init__(self, version: Version, flow_sid: str): } self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) + def _create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + 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, to: str, from_: str, parameters: Union[object, object] = values.unset ) -> ExecutionInstance: @@ -405,6 +658,41 @@ def create( :returns: The created ExecutionInstance """ + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def create_with_http_info( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "To": to, @@ -412,15 +700,14 @@ def create( "Parameters": serialize.object(parameters), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ExecutionInstance( - self._version, payload, flow_sid=self._solution["flow_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( @@ -435,23 +722,32 @@ async def create_async( :returns: The created ExecutionInstance """ - data = values.of( - { - "To": to, - "From": from_, - "Parameters": serialize.object(parameters), - } + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] ) - return ExecutionInstance( + 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, @@ -519,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, @@ -542,6 +902,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created_from=date_created_from, @@ -574,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( @@ -584,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, @@ -614,8 +1038,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ExecutionPage(self._version, response, self._solution) + 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 ExecutionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -647,10 +1077,96 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ExecutionPage(self._version, response, self._solution) + 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: """ @@ -662,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: """ @@ -674,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 d84431d12a..d12c6b3f93 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_context.py +++ b/twilio/rest/studio/v1/flow/execution/execution_context.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class ExecutionContextInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. :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. @@ -49,6 +49,7 @@ def __init__( "flow_sid": flow_sid, "execution_sid": execution_sid, } + self._context: Optional[ExecutionContextContext] = None @property @@ -85,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 @@ -96,6 +115,7 @@ def __repr__(self) -> str: class ExecutionContextContext(InstanceContext): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ Initialize the ExecutionContextContext @@ -115,6 +135,22 @@ def __init__(self, version: Version, flow_sid: str, execution_sid: str): **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) -> ExecutionContextInstance: """ Fetch the ExecutionContextInstance @@ -122,18 +158,45 @@ def fetch(self) -> ExecutionContextInstance: :returns: The fetched ExecutionContextInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], ) - return ExecutionContextInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionContextInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExecutionContextInstance: """ @@ -142,18 +205,29 @@ async def fetch_async(self) -> ExecutionContextInstance: :returns: The fetched ExecutionContextInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], ) - return ExecutionContextInstance( + 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: """ @@ -166,6 +240,7 @@ def __repr__(self) -> str: class ExecutionContextList(ListResource): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ Initialize the ExecutionContextList 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 462e5322b4..d09adb9984 100644 --- a/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py +++ b/twilio/rest/studio/v1/flow/execution/execution_step/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,16 +27,17 @@ class ExecutionStepInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the ExecutionStep resource. :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. @@ -57,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") ) @@ -75,6 +78,7 @@ def __init__( "execution_sid": execution_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionStepContext] = None @property @@ -112,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: """ @@ -130,6 +152,7 @@ def __repr__(self) -> str: class ExecutionStepContext(InstanceContext): + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): """ Initialize the ExecutionStepContext @@ -153,6 +176,22 @@ def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str self._step_context: Optional[ExecutionStepContextList] = None + 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) -> ExecutionStepInstance: """ Fetch the ExecutionStepInstance @@ -160,19 +199,47 @@ def fetch(self) -> ExecutionStepInstance: :returns: The fetched ExecutionStepInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) - return ExecutionStepInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExecutionStepInstance: """ @@ -181,19 +248,31 @@ async def fetch_async(self) -> ExecutionStepInstance: :returns: The fetched ExecutionStepInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) - return ExecutionStepInstance( + 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: @@ -220,12 +299,14 @@ def __repr__(self) -> str: class ExecutionStepPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: """ Build an instance of ExecutionStepInstance :param payload: Payload response from the API """ + return ExecutionStepInstance( self._version, payload, @@ -243,6 +324,7 @@ def __repr__(self) -> str: class ExecutionStepList(ListResource): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ Initialize the ExecutionStepList @@ -313,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, @@ -332,6 +464,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -358,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( @@ -366,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, @@ -390,8 +574,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ExecutionStepPage(self._version, response, self._solution) + 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 ExecutionStepPage(self._version, response, solution=self._solution) async def page_async( self, @@ -417,10 +607,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ExecutionStepPage(self._version, response, self._solution) + 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: """ @@ -432,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: """ @@ -444,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 1463adec6b..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 @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class ExecutionStepContextInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. :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. @@ -53,6 +53,7 @@ def __init__( "execution_sid": execution_sid, "step_sid": step_sid, } + self._context: Optional[ExecutionStepContextContext] = None @property @@ -90,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 @@ -101,6 +120,7 @@ def __repr__(self) -> str: class ExecutionStepContextContext(InstanceContext): + def __init__( self, version: Version, flow_sid: str, execution_sid: str, step_sid: str ): @@ -124,6 +144,22 @@ def __init__( **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) -> ExecutionStepContextInstance: """ Fetch the ExecutionStepContextInstance @@ -131,19 +167,47 @@ def fetch(self) -> ExecutionStepContextInstance: :returns: The fetched ExecutionStepContextInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], ) - return ExecutionStepContextInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepContextInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExecutionStepContextInstance: """ @@ -152,19 +216,31 @@ async def fetch_async(self) -> ExecutionStepContextInstance: :returns: The fetched ExecutionStepContextInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], ) - return ExecutionStepContextInstance( + 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: """ @@ -177,6 +253,7 @@ def __repr__(self) -> str: class ExecutionStepContextList(ListResource): + def __init__( self, version: Version, flow_sid: str, execution_sid: str, step_sid: str ): diff --git a/twilio/rest/studio/v2/__init__.py b/twilio/rest/studio/v2/__init__.py index 2ad61768ad..83ccc8e0a9 100644 --- a/twilio/rest/studio/v2/__init__.py +++ b/twilio/rest/studio/v2/__init__.py @@ -20,6 +20,7 @@ class V2(Version): + def __init__(self, domain: Domain): """ Initialize the V2 version of Studio diff --git a/twilio/rest/studio/v2/flow/__init__.py b/twilio/rest/studio/v2/flow/__init__.py index 408e29cc7b..c13e10be4c 100644 --- a/twilio/rest/studio/v2/flow/__init__.py +++ b/twilio/rest/studio/v2/flow/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,6 +27,7 @@ class FlowInstance(InstanceResource): + class Status(object): DRAFT = "draft" PUBLISHED = "published" @@ -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,14 +58,15 @@ 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") self.revision: Optional[int] = deserialize.integer(payload.get("revision")) self.commit_message: Optional[str] = payload.get("commit_message") self.valid: Optional[bool] = payload.get("valid") - self.errors: Optional[List[object]] = payload.get("errors") - self.warnings: Optional[List[object]] = payload.get("warnings") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") + self.warnings: Optional[List[Dict[str, object]]] = payload.get("warnings") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -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 @@ -210,6 +310,7 @@ def __repr__(self) -> str: class FlowContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the FlowContext @@ -229,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 @@ -236,9 +351,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -248,9 +385,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FlowInstance 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) -> FlowInstance: @@ -260,17 +421,43 @@ def fetch(self) -> FlowInstance: :returns: The fetched FlowInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FlowInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FlowInstance: """ @@ -279,17 +466,61 @@ async def fetch_async(self) -> FlowInstance: :returns: The fetched FlowInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return FlowInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FlowInstance( + 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, + author_sid: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "FriendlyName": friendly_name, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + "AuthorSid": author_sid, + } + ) + 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, @@ -297,6 +528,7 @@ def update( 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 @@ -305,25 +537,81 @@ 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 """ + 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( { "Status": status, "FriendlyName": friendly_name, "Definition": serialize.object(definition), "CommitMessage": commit_message, + "AuthorSid": author_sid, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return FlowInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -331,6 +619,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 @@ -339,25 +628,47 @@ 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 """ - data = values.of( - { - "Status": status, - "FriendlyName": friendly_name, - "Definition": serialize.object(definition), - "CommitMessage": commit_message, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return FlowInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -406,12 +717,14 @@ def __repr__(self) -> str: class FlowPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> FlowInstance: """ Build an instance of FlowInstance :param payload: Payload response from the API """ + return FlowInstance(self._version, payload) def __repr__(self) -> str: @@ -424,6 +737,7 @@ def __repr__(self) -> str: class FlowList(ListResource): + def __init__(self, version: Version): """ Initialize the FlowList @@ -435,12 +749,47 @@ def __init__(self, version: Version): self._uri = "/Flows" + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Status": status, + "Definition": serialize.object(definition), + "CommitMessage": commit_message, + "AuthorSid": author_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, friendly_name: str, status: "FlowInstance.Status", definition: object, commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, ) -> FlowInstance: """ Create the FlowInstance @@ -449,25 +798,81 @@ def create( :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( { "FriendlyName": friendly_name, "Status": status, "Definition": serialize.object(definition), "CommitMessage": commit_message, + "AuthorSid": author_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return FlowInstance(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, @@ -475,6 +880,7 @@ async def create_async( status: "FlowInstance.Status", definition: object, commit_message: Union[str, object] = values.unset, + author_sid: Union[str, object] = values.unset, ) -> FlowInstance: """ Asynchronously create the FlowInstance @@ -483,25 +889,47 @@ async def create_async( :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 """ - data = values.of( - { - "FriendlyName": friendly_name, - "Status": status, - "Definition": serialize.object(definition), - "CommitMessage": commit_message, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return FlowInstance(self._version, payload) + :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, @@ -553,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, @@ -572,6 +1050,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -598,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( @@ -606,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, @@ -630,7 +1160,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 FlowPage(self._version, response) async def page_async( @@ -657,11 +1193,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 1173683525..0a0bfa6fed 100644 --- a/twilio/rest/studio/v2/flow/execution/__init__.py +++ b/twilio/rest/studio/v2/flow/execution/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,6 +26,7 @@ class ExecutionInstance(InstanceResource): + class Status(object): ACTIVE = "active" ENDED = "ended" @@ -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: """ @@ -178,6 +250,7 @@ def __repr__(self) -> str: class ExecutionContext(InstanceContext): + def __init__(self, version: Version, flow_sid: str, sid: str): """ Initialize the ExecutionContext @@ -198,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 @@ -205,9 +292,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -217,9 +326,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ExecutionInstance 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) -> ExecutionInstance: @@ -229,18 +362,45 @@ def fetch(self) -> ExecutionInstance: :returns: The fetched ExecutionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExecutionInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + sid=self._solution["sid"], ) - return ExecutionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExecutionInstance: """ @@ -249,12 +409,7 @@ async def fetch_async(self) -> ExecutionInstance: :returns: The fetched ExecutionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return ExecutionInstance( self._version, payload, @@ -262,26 +417,54 @@ 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( { "Status": status, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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: "ExecutionInstance.Status") -> ExecutionInstance: + """ + Update the ExecutionInstance + + :param status: + + :returns: The updated ExecutionInstance + """ + payload, _, _ = self._update(status=status) return ExecutionInstance( self._version, payload, @@ -289,28 +472,57 @@ 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( { "Status": status, } ) + 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, + 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, @@ -318,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: """ @@ -355,12 +586,14 @@ def __repr__(self) -> str: class ExecutionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ExecutionInstance: """ Build an instance of ExecutionInstance :param payload: Payload response from the API """ + return ExecutionInstance( self._version, payload, flow_sid=self._solution["flow_sid"] ) @@ -375,6 +608,7 @@ def __repr__(self) -> str: class ExecutionList(ListResource): + def __init__(self, version: Version, flow_sid: str): """ Initialize the ExecutionList @@ -391,6 +625,33 @@ def __init__(self, version: Version, flow_sid: str): } self._uri = "/Flows/{flow_sid}/Executions".format(**self._solution) + def _create( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "To": to, + "From": from_, + "Parameters": serialize.object(parameters), + } + ) + 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, to: str, from_: str, parameters: Union[object, object] = values.unset ) -> ExecutionInstance: @@ -403,6 +664,41 @@ def create( :returns: The created ExecutionInstance """ + payload, _, _ = self._create(to=to, from_=from_, parameters=parameters) + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] + ) + + def create_with_http_info( + self, to: str, from_: str, parameters: Union[object, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "To": to, @@ -410,15 +706,14 @@ def create( "Parameters": serialize.object(parameters), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ExecutionInstance( - self._version, payload, flow_sid=self._solution["flow_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( @@ -433,26 +728,36 @@ async def create_async( :returns: The created ExecutionInstance """ - data = values.of( - { - "To": to, - "From": from_, - "Parameters": serialize.object(parameters), - } + payload, _, _ = await self._create_async( + to=to, from_=from_, parameters=parameters ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return ExecutionInstance( + self._version, payload, flow_sid=self._solution["flow_sid"] ) - return ExecutionInstance( + 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, @@ -464,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() @@ -477,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"], @@ -486,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, @@ -497,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() @@ -510,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"], @@ -517,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, @@ -529,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 @@ -540,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, @@ -551,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, @@ -561,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 @@ -572,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, @@ -582,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, @@ -594,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 @@ -604,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, @@ -612,11 +1071,18 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ExecutionPage(self._version, response, self._solution) + 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 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, @@ -627,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 @@ -637,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, @@ -645,10 +1113,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ExecutionPage(self._version, response, self._solution) + 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: """ @@ -660,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: """ @@ -672,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 47628b1ea9..d27773667f 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_context.py +++ b/twilio/rest/studio/v2/flow/execution/execution_context.py @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class ExecutionContextInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionContext resource. :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. @@ -49,6 +49,7 @@ def __init__( "flow_sid": flow_sid, "execution_sid": execution_sid, } + self._context: Optional[ExecutionContextContext] = None @property @@ -85,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 @@ -96,6 +115,7 @@ def __repr__(self) -> str: class ExecutionContextContext(InstanceContext): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ Initialize the ExecutionContextContext @@ -115,6 +135,22 @@ def __init__(self, version: Version, flow_sid: str, execution_sid: str): **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) -> ExecutionContextInstance: """ Fetch the ExecutionContextInstance @@ -122,18 +158,45 @@ def fetch(self) -> ExecutionContextInstance: :returns: The fetched ExecutionContextInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], ) - return ExecutionContextInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionContextInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExecutionContextInstance: """ @@ -142,18 +205,29 @@ async def fetch_async(self) -> ExecutionContextInstance: :returns: The fetched ExecutionContextInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ExecutionContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], ) - return ExecutionContextInstance( + 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: """ @@ -166,6 +240,7 @@ def __repr__(self) -> str: class ExecutionContextList(ListResource): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ Initialize the ExecutionContextList 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 7b43ad5eee..57c14a8ab6 100644 --- a/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py +++ b/twilio/rest/studio/v2/flow/execution/execution_step/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,16 +27,17 @@ class ExecutionStepInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the ExecutionStep resource. :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. @@ -57,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") ) @@ -75,6 +78,7 @@ def __init__( "execution_sid": execution_sid, "sid": sid or self.sid, } + self._context: Optional[ExecutionStepContext] = None @property @@ -112,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: """ @@ -130,6 +152,7 @@ def __repr__(self) -> str: class ExecutionStepContext(InstanceContext): + def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str): """ Initialize the ExecutionStepContext @@ -153,6 +176,22 @@ def __init__(self, version: Version, flow_sid: str, execution_sid: str, sid: str self._step_context: Optional[ExecutionStepContextList] = None + 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) -> ExecutionStepInstance: """ Fetch the ExecutionStepInstance @@ -160,19 +199,47 @@ def fetch(self) -> ExecutionStepInstance: :returns: The fetched ExecutionStepInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) - return ExecutionStepInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExecutionStepInstance: """ @@ -181,19 +248,31 @@ async def fetch_async(self) -> ExecutionStepInstance: :returns: The fetched ExecutionStepInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ExecutionStepInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + sid=self._solution["sid"], ) - return ExecutionStepInstance( + 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: @@ -220,12 +299,14 @@ def __repr__(self) -> str: class ExecutionStepPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ExecutionStepInstance: """ Build an instance of ExecutionStepInstance :param payload: Payload response from the API """ + return ExecutionStepInstance( self._version, payload, @@ -243,6 +324,7 @@ def __repr__(self) -> str: class ExecutionStepList(ListResource): + def __init__(self, version: Version, flow_sid: str, execution_sid: str): """ Initialize the ExecutionStepList @@ -313,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, @@ -332,6 +464,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -358,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( @@ -366,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, @@ -390,8 +574,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ExecutionStepPage(self._version, response, self._solution) + 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 ExecutionStepPage(self._version, response, solution=self._solution) async def page_async( self, @@ -417,10 +607,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ExecutionStepPage(self._version, response, self._solution) + 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: """ @@ -432,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: """ @@ -444,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 5a88321590..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 @@ -12,8 +12,9 @@ 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 @@ -21,7 +22,6 @@ class ExecutionStepContextInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ExecutionStepContext resource. :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. @@ -53,6 +53,7 @@ def __init__( "execution_sid": execution_sid, "step_sid": step_sid, } + self._context: Optional[ExecutionStepContextContext] = None @property @@ -90,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 @@ -101,6 +120,7 @@ def __repr__(self) -> str: class ExecutionStepContextContext(InstanceContext): + def __init__( self, version: Version, flow_sid: str, execution_sid: str, step_sid: str ): @@ -124,6 +144,22 @@ def __init__( **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) -> ExecutionStepContextInstance: """ Fetch the ExecutionStepContextInstance @@ -131,19 +167,47 @@ def fetch(self) -> ExecutionStepContextInstance: :returns: The fetched ExecutionStepContextInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], ) - return ExecutionStepContextInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ExecutionStepContextInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ExecutionStepContextInstance: """ @@ -152,19 +216,31 @@ async def fetch_async(self) -> ExecutionStepContextInstance: :returns: The fetched ExecutionStepContextInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ExecutionStepContextInstance( + self._version, + payload, + flow_sid=self._solution["flow_sid"], + execution_sid=self._solution["execution_sid"], + step_sid=self._solution["step_sid"], ) - return ExecutionStepContextInstance( + 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: """ @@ -177,6 +253,7 @@ def __repr__(self) -> str: class ExecutionStepContextList(ListResource): + def __init__( self, version: Version, flow_sid: str, execution_sid: str, step_sid: str ): diff --git a/twilio/rest/studio/v2/flow/flow_revision.py b/twilio/rest/studio/v2/flow/flow_revision.py index a9a5394a4f..046e08d7c6 100644 --- a/twilio/rest/studio/v2/flow/flow_revision.py +++ b/twilio/rest/studio/v2/flow/flow_revision.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class FlowRevisionInstance(InstanceResource): + class Status(object): DRAFT = "draft" PUBLISHED = "published" @@ -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,13 +56,14 @@ 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") self.revision: Optional[int] = deserialize.integer(payload.get("revision")) self.commit_message: Optional[str] = payload.get("commit_message") self.valid: Optional[bool] = payload.get("valid") - self.errors: Optional[List[object]] = payload.get("errors") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -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 @@ -120,6 +142,7 @@ def __repr__(self) -> str: class FlowRevisionContext(InstanceContext): + def __init__(self, version: Version, sid: str, revision: str): """ Initialize the FlowRevisionContext @@ -137,6 +160,22 @@ def __init__(self, version: Version, sid: str, revision: str): } self._uri = "/Flows/{sid}/Revisions/{revision}".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) -> FlowRevisionInstance: """ Fetch the FlowRevisionInstance @@ -144,18 +183,45 @@ def fetch(self) -> FlowRevisionInstance: :returns: The fetched FlowRevisionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], ) - return FlowRevisionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowRevisionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FlowRevisionInstance: """ @@ -164,18 +230,29 @@ async def fetch_async(self) -> FlowRevisionInstance: :returns: The fetched FlowRevisionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return FlowRevisionInstance( + self._version, + payload, + sid=self._solution["sid"], + revision=self._solution["revision"], ) - return FlowRevisionInstance( + 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: """ @@ -188,12 +265,14 @@ def __repr__(self) -> str: class FlowRevisionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> FlowRevisionInstance: """ Build an instance of FlowRevisionInstance :param payload: Payload response from the API """ + return FlowRevisionInstance(self._version, payload, sid=self._solution["sid"]) def __repr__(self) -> str: @@ -206,6 +285,7 @@ def __repr__(self) -> str: class FlowRevisionList(ListResource): + def __init__(self, version: Version, sid: str): """ Initialize the FlowRevisionList @@ -272,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, @@ -291,6 +421,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -317,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( @@ -325,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, @@ -349,8 +531,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return FlowRevisionPage(self._version, response, self._solution) + 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 FlowRevisionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -376,10 +564,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return FlowRevisionPage(self._version, response, self._solution) + 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: """ @@ -391,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: """ @@ -403,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 d5dbee7d68..c030529dde 100644 --- a/twilio/rest/studio/v2/flow/flow_test_user.py +++ b/twilio/rest/studio/v2/flow/flow_test_user.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - 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 @@ -22,7 +22,6 @@ class FlowTestUserInstance(InstanceResource): - """ :ivar sid: Unique identifier of the flow. :ivar test_users: List of test user identities that can test draft versions of the flow. @@ -39,6 +38,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], sid: str): self._solution = { "sid": sid, } + self._context: Optional[FlowTestUserContext] = None @property @@ -74,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 @@ -98,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 @@ -109,6 +151,7 @@ def __repr__(self) -> str: class FlowTestUserContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the FlowTestUserContext @@ -124,6 +167,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Flows/{sid}/TestUsers".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) -> FlowTestUserInstance: """ Fetch the FlowTestUserInstance @@ -131,17 +190,43 @@ def fetch(self) -> FlowTestUserInstance: :returns: The fetched FlowTestUserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FlowTestUserInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FlowTestUserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FlowTestUserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FlowTestUserInstance: """ @@ -150,62 +235,124 @@ async def fetch_async(self) -> FlowTestUserInstance: :returns: The fetched FlowTestUserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + 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( { "TestUsers": serialize.map(test_users, lambda e: e), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "TestUsers": serialize.map(test_users, lambda e: e), } ) + 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, + 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 @@ -217,6 +364,7 @@ def __repr__(self) -> str: class FlowTestUserList(ListResource): + def __init__(self, version: Version, sid: str): """ Initialize the FlowTestUserList diff --git a/twilio/rest/studio/v2/flow_validate.py b/twilio/rest/studio/v2/flow_validate.py index 74ddfa2362..390ad74ca3 100644 --- a/twilio/rest/studio/v2/flow_validate.py +++ b/twilio/rest/studio/v2/flow_validate.py @@ -12,9 +12,9 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -22,6 +22,7 @@ class FlowValidateInstance(InstanceResource): + class Status(object): DRAFT = "draft" PUBLISHED = "published" @@ -46,6 +47,7 @@ def __repr__(self) -> str: class FlowValidateList(ListResource): + def __init__(self, version: Version): """ Initialize the FlowValidateList @@ -57,23 +59,20 @@ 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 - - :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 update operation - :returns: The created FlowValidateInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -82,32 +81,81 @@ def update( "CommitMessage": commit_message, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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: 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( { "FriendlyName": friendly_name, @@ -116,15 +164,67 @@ async def update_async( "CommitMessage": commit_message, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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: 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/SupersimBase.py b/twilio/rest/supersim/SupersimBase.py index d85c382641..dd73d12223 100644 --- a/twilio/rest/supersim/SupersimBase.py +++ b/twilio/rest/supersim/SupersimBase.py @@ -17,6 +17,7 @@ class SupersimBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Supersim Domain diff --git a/twilio/rest/supersim/v1/__init__.py b/twilio/rest/supersim/v1/__init__.py index 480787bcab..2336da2616 100644 --- a/twilio/rest/supersim/v1/__init__.py +++ b/twilio/rest/supersim/v1/__init__.py @@ -27,6 +27,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Supersim diff --git a/twilio/rest/supersim/v1/esim_profile.py b/twilio/rest/supersim/v1/esim_profile.py index 2b8472aa84..f60d8f11d0 100644 --- a/twilio/rest/supersim/v1/esim_profile.py +++ b/twilio/rest/supersim/v1/esim_profile.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class EsimProfileInstance(InstanceResource): + class Status(object): NEW = "new" RESERVING = "reserving" @@ -36,7 +37,7 @@ class Status(object): :ivar sid: The unique string that we created to identify the eSIM Profile resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the eSIM Profile resource belongs. :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/Subscriber_identity_module#ICCID) associated with the Sim resource. - :ivar sim_sid: The SID of the [Sim](https://www.twilio.com/docs/wireless/api/sim-resource) resource that this eSIM Profile controls. + :ivar sim_sid: The SID of the [Sim](https://www.twilio.com/docs/iot/supersim/api/sim-resource) resource that this eSIM Profile controls. :ivar status: :ivar eid: Identifier of the eUICC that can claim the eSIM Profile. :ivar smdp_plus_address: Address of the SM-DP+ server from which the Profile will be downloaded. The URL will appear once the eSIM Profile reaches the status `available`. @@ -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 @@ -122,6 +142,7 @@ def __repr__(self) -> str: class EsimProfileContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the EsimProfileContext @@ -137,6 +158,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/ESimProfiles/{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) -> EsimProfileInstance: """ Fetch the EsimProfileInstance @@ -144,17 +181,43 @@ def fetch(self) -> EsimProfileInstance: :returns: The fetched EsimProfileInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EsimProfileInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EsimProfileInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EsimProfileInstance: """ @@ -163,17 +226,27 @@ async def fetch_async(self) -> EsimProfileInstance: :returns: The fetched EsimProfileInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EsimProfileInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EsimProfileInstance( + 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: """ @@ -186,12 +259,14 @@ def __repr__(self) -> str: class EsimProfilePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EsimProfileInstance: """ Build an instance of EsimProfileInstance :param payload: Payload response from the API """ + return EsimProfileInstance(self._version, payload) def __repr__(self) -> str: @@ -204,6 +279,7 @@ def __repr__(self) -> str: class EsimProfileList(ListResource): + def __init__(self, version: Version): """ Initialize the EsimProfileList @@ -215,6 +291,38 @@ def __init__(self, version: Version): self._uri = "/ESimProfiles" + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "GenerateMatchingId": serialize.boolean_to_string(generate_matching_id), + "Eid": eid, + } + ) + 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, callback_url: Union[str, object] = values.unset, @@ -232,22 +340,71 @@ def create( :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( { "CallbackUrl": callback_url, "CallbackMethod": callback_method, - "GenerateMatchingId": generate_matching_id, + "GenerateMatchingId": serialize.boolean_to_string(generate_matching_id), "Eid": eid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return EsimProfileInstance(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, @@ -266,22 +423,39 @@ async def create_async( :returns: The created EsimProfileInstance """ - data = values.of( - { - "CallbackUrl": callback_url, - "CallbackMethod": callback_method, - "GenerateMatchingId": generate_matching_id, - "Eid": eid, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return EsimProfileInstance(self._version, payload) + :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, @@ -298,7 +472,7 @@ def stream( The results are returned as a generator, so this operation is memory efficient. :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/wireless/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :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 @@ -331,7 +505,7 @@ async def stream_async( The results are returned as a generator, so this operation is memory efficient. :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/wireless/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :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 @@ -349,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, @@ -363,7 +601,7 @@ def list( memory before returning. :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/wireless/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :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 @@ -374,6 +612,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( eid=eid, @@ -398,7 +637,7 @@ async def list_async( memory before returning. :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/wireless/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :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 @@ -409,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( @@ -420,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, @@ -434,7 +742,7 @@ def page( Request is executed immediately :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/wireless/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :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 @@ -453,7 +761,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 EsimProfilePage(self._version, response) async def page_async( @@ -470,7 +784,7 @@ async def page_async( Request is executed immediately :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/wireless/api/sim-resource) resource by providing the SIM SID. Will always return an array with either 1 or 0 records. + :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 @@ -489,11 +803,103 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 7ba3ce7a12..7f17059350 100644 --- a/twilio/rest/supersim/v1/fleet.py +++ b/twilio/rest/supersim/v1/fleet.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class FleetInstance(InstanceResource): + class DataMetering(object): PAYG = "payg" @@ -35,9 +36,9 @@ class DataMetering(object): :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 Fleet resource. :ivar data_enabled: Defines whether SIMs in the Fleet are capable of using 2G/3G/4G/LTE/CAT-M data connectivity. Defaults to `true`. - :ivar 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). + :ivar 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 250MB. :ivar data_metering: - :ivar sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `true`. + :ivar sms_commands_enabled: Defines whether SIMs in the Fleet are capable of sending and receiving machine-to-machine SMS via Commands. Defaults to `false`. :ivar 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. :ivar 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`. :ivar network_access_profile_sid: The SID of the Network Access Profile that controls which cellular networks the Fleet's SIMs can connect to. @@ -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 @@ -189,6 +275,7 @@ def __repr__(self) -> str: class FleetContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the FleetContext @@ -204,6 +291,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Fleets/{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) -> FleetInstance: """ Fetch the FleetInstance @@ -211,17 +314,43 @@ def fetch(self) -> FleetInstance: :returns: The fetched FleetInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FleetInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FleetInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FleetInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FleetInstance: """ @@ -230,17 +359,65 @@ async def fetch_async(self) -> FleetInstance: :returns: The fetched FleetInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return FleetInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return FleetInstance( + 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, + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "NetworkAccessProfile": network_access_profile, + "IpCommandsUrl": ip_commands_url, + "IpCommandsMethod": ip_commands_method, + "SmsCommandsUrl": sms_commands_url, + "SmsCommandsMethod": sms_commands_method, + "DataLimit": data_limit, + } + ) + 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, @@ -265,6 +442,69 @@ def update( :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( { "UniqueName": unique_name, @@ -276,14 +516,15 @@ def update( "DataLimit": data_limit, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return FleetInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -308,25 +549,51 @@ async def update_async( :returns: The updated FleetInstance """ - data = values.of( - { - "UniqueName": unique_name, - "NetworkAccessProfile": network_access_profile, - "IpCommandsUrl": ip_commands_url, - "IpCommandsMethod": ip_commands_method, - "SmsCommandsUrl": sms_commands_url, - "SmsCommandsMethod": sms_commands_method, - "DataLimit": data_limit, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return FleetInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -339,12 +606,14 @@ def __repr__(self) -> str: class FleetPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> FleetInstance: """ Build an instance of FleetInstance :param payload: Payload response from the API """ + return FleetInstance(self._version, payload) def __repr__(self) -> str: @@ -357,6 +626,7 @@ def __repr__(self) -> str: class FleetList(ListResource): + def __init__(self, version: Version): """ Initialize the FleetList @@ -368,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, @@ -379,46 +649,39 @@ 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 + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "NetworkAccessProfile": network_access_profile, "UniqueName": unique_name, - "DataEnabled": data_enabled, + "DataEnabled": serialize.boolean_to_string(data_enabled), "DataLimit": data_limit, "IpCommandsUrl": ip_commands_url, "IpCommandsMethod": ip_commands_method, - "SmsCommandsEnabled": sms_commands_enabled, + "SmsCommandsEnabled": serialize.boolean_to_string(sms_commands_enabled), "SmsCommandsUrl": sms_commands_url, "SmsCommandsMethod": sms_commands_method, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return FleetInstance(self._version, payload) + headers["Accept"] = "application/json" - async def create_async( - self, + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( + self, network_access_profile: str, unique_name: Union[str, object] = values.unset, data_enabled: Union[bool, object] = values.unset, @@ -430,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. @@ -444,28 +707,183 @@ async def create_async( :returns: The created FleetInstance """ + 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, - "DataEnabled": data_enabled, + "DataEnabled": serialize.boolean_to_string(data_enabled), "DataLimit": data_limit, "IpCommandsUrl": ip_commands_url, "IpCommandsMethod": ip_commands_method, - "SmsCommandsEnabled": sms_commands_enabled, + "SmsCommandsEnabled": serialize.boolean_to_string(sms_commands_enabled), "SmsCommandsUrl": sms_commands_url, "SmsCommandsMethod": sms_commands_method, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -524,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, @@ -545,6 +1019,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( network_access_profile=network_access_profile, @@ -574,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( @@ -583,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, @@ -610,7 +1142,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 FleetPage(self._version, response) async def page_async( @@ -640,11 +1178,91 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 331ef26de2..2af10f7bfb 100644 --- a/twilio/rest/supersim/v1/ip_command.py +++ b/twilio/rest/supersim/v1/ip_command.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class IpCommandInstance(InstanceResource): + class Direction(object): TO_SIM = "to_sim" FROM_SIM = "from_sim" @@ -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 @@ -132,6 +152,7 @@ def __repr__(self) -> str: class IpCommandContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the IpCommandContext @@ -147,6 +168,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/IpCommands/{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) -> IpCommandInstance: """ Fetch the IpCommandInstance @@ -154,17 +191,43 @@ def fetch(self) -> IpCommandInstance: :returns: The fetched IpCommandInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return IpCommandInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpCommandInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> IpCommandInstance: """ @@ -173,17 +236,27 @@ async def fetch_async(self) -> IpCommandInstance: :returns: The fetched IpCommandInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return IpCommandInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return IpCommandInstance( + 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: """ @@ -196,12 +269,14 @@ def __repr__(self) -> str: class IpCommandPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> IpCommandInstance: """ Build an instance of IpCommandInstance :param payload: Payload response from the API """ + return IpCommandInstance(self._version, payload) def __repr__(self) -> str: @@ -214,6 +289,7 @@ def __repr__(self) -> str: class IpCommandList(ListResource): + def __init__(self, version: Version): """ Initialize the IpCommandList @@ -225,6 +301,42 @@ def __init__(self, version: Version): self._uri = "/IpCommands" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "DevicePort": device_port, + "PayloadType": payload_type, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + } + ) + 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, sim: str, @@ -246,6 +358,64 @@ def create( :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( { "Sim": sim, @@ -256,14 +426,15 @@ def create( "CallbackMethod": callback_method, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return IpCommandInstance(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, @@ -286,24 +457,47 @@ async def create_async( :returns: The created IpCommandInstance """ - data = values.of( - { - "Sim": sim, - "Payload": payload, - "DevicePort": device_port, - "PayloadType": payload_type, - "CallbackUrl": callback_url, - "CallbackMethod": callback_method, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return IpCommandInstance(self._version, payload) + :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, @@ -322,7 +516,7 @@ def stream( :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/wireless/api/ipcommand-resource#status-values) for a description of each. + :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 @@ -361,7 +555,7 @@ async def stream_async( :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/wireless/api/ipcommand-resource#status-values) for a description of each. + :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 @@ -383,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, @@ -399,7 +669,7 @@ def list( :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/wireless/api/ipcommand-resource#status-values) for a description of each. + :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 @@ -410,6 +680,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -437,7 +708,7 @@ async def list_async( :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/wireless/api/ipcommand-resource#status-values) for a description of each. + :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 @@ -448,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( @@ -460,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, @@ -476,7 +822,7 @@ def page( :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/wireless/api/ipcommand-resource#status-values) for a description of each. + :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 @@ -496,7 +842,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 IpCommandPage(self._version, response) async def page_async( @@ -515,7 +867,7 @@ async def page_async( :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/wireless/api/ipcommand-resource#status-values) for a description of each. + :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 @@ -535,11 +887,109 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 7364105c88..c89787b807 100644 --- a/twilio/rest/supersim/v1/network.py +++ b/twilio/rest/supersim/v1/network.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class NetworkInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Network resource. :ivar friendly_name: A human readable identifier of this resource. @@ -41,11 +40,12 @@ def __init__( self.friendly_name: Optional[str] = payload.get("friendly_name") self.url: Optional[str] = payload.get("url") self.iso_country: Optional[str] = payload.get("iso_country") - self.identifiers: Optional[List[object]] = payload.get("identifiers") + self.identifiers: Optional[List[Dict[str, object]]] = payload.get("identifiers") self._solution = { "sid": sid or self.sid, } + self._context: Optional[NetworkContext] = None @property @@ -81,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 @@ -92,6 +110,7 @@ def __repr__(self) -> str: class NetworkContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the NetworkContext @@ -107,6 +126,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Networks/{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) -> NetworkInstance: """ Fetch the NetworkInstance @@ -114,17 +149,43 @@ def fetch(self) -> NetworkInstance: :returns: The fetched NetworkInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return NetworkInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> NetworkInstance: """ @@ -133,17 +194,27 @@ async def fetch_async(self) -> NetworkInstance: :returns: The fetched NetworkInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return NetworkInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return NetworkInstance( + 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: """ @@ -156,12 +227,14 @@ def __repr__(self) -> str: class NetworkPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> NetworkInstance: """ Build an instance of NetworkInstance :param payload: Payload response from the API """ + return NetworkInstance(self._version, payload) def __repr__(self) -> str: @@ -174,6 +247,7 @@ def __repr__(self) -> str: class NetworkList(ListResource): + def __init__(self, version: Version): """ Initialize the NetworkList @@ -251,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, @@ -276,6 +414,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( iso_country=iso_country, @@ -311,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( @@ -322,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, @@ -355,7 +563,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 NetworkPage(self._version, response) async def page_async( @@ -391,11 +605,103 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 0712dbe653..02c55897e5 100644 --- a/twilio/rest/supersim/v1/network_access_profile/__init__.py +++ b/twilio/rest/supersim/v1/network_access_profile/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class NetworkAccessProfileInstance(InstanceResource): - """ :ivar sid: The unique string that identifies the Network Access Profile 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. @@ -58,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[NetworkAccessProfileContext] = None @property @@ -93,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": @@ -121,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: """ @@ -139,6 +185,7 @@ def __repr__(self) -> str: class NetworkAccessProfileContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the NetworkAccessProfileContext @@ -156,6 +203,22 @@ def __init__(self, version: Version, sid: str): self._networks: Optional[NetworkAccessProfileNetworkList] = None + 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) -> NetworkAccessProfileInstance: """ Fetch the NetworkAccessProfileInstance @@ -163,17 +226,43 @@ def fetch(self) -> NetworkAccessProfileInstance: :returns: The fetched NetworkAccessProfileInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return NetworkAccessProfileInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> NetworkAccessProfileInstance: """ @@ -182,17 +271,50 @@ async def fetch_async(self) -> NetworkAccessProfileInstance: :returns: The fetched NetworkAccessProfileInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return NetworkAccessProfileInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return NetworkAccessProfileInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the NetworkAccessProfileInstance and return response metadata + + + :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( + { + "UniqueName": unique_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, unique_name: Union[str, object] = values.unset @@ -204,20 +326,50 @@ def update( :returns: The updated NetworkAccessProfileInstance """ + payload, _, _ = self._update(unique_name=unique_name) + return NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + self, unique_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "UniqueName": unique_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return NetworkAccessProfileInstance( - self._version, payload, sid=self._solution["sid"] + 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( @@ -230,21 +382,28 @@ async def update_async( :returns: The updated NetworkAccessProfileInstance """ - data = values.of( - { - "UniqueName": unique_name, - } + payload, _, _ = await self._update_async(unique_name=unique_name) + return NetworkAccessProfileInstance( + self._version, payload, sid=self._solution["sid"] ) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return NetworkAccessProfileInstance( + :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: @@ -269,12 +428,14 @@ def __repr__(self) -> str: class NetworkAccessProfilePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> NetworkAccessProfileInstance: """ Build an instance of NetworkAccessProfileInstance :param payload: Payload response from the API """ + return NetworkAccessProfileInstance(self._version, payload) def __repr__(self) -> str: @@ -287,6 +448,7 @@ def __repr__(self) -> str: class NetworkAccessProfileList(ListResource): + def __init__(self, version: Version): """ Initialize the NetworkAccessProfileList @@ -298,6 +460,34 @@ def __init__(self, version: Version): self._uri = "/NetworkAccessProfiles" + def _create( + self, + unique_name: Union[str, object] = values.unset, + networks: Union[List[str], object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "Networks": serialize.map(networks, lambda e: 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.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def create( self, unique_name: Union[str, object] = values.unset, @@ -311,20 +501,55 @@ def create( :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( { "UniqueName": unique_name, "Networks": serialize.map(networks, lambda e: e), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return NetworkAccessProfileInstance(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, @@ -339,20 +564,29 @@ async def create_async( :returns: The created NetworkAccessProfileInstance """ - data = values.of( - { - "UniqueName": unique_name, - "Networks": serialize.map(networks, lambda e: e), - } + payload, _, _ = await self._create_async( + unique_name=unique_name, networks=networks ) + return NetworkAccessProfileInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return NetworkAccessProfileInstance(self._version, payload) + :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, @@ -404,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, @@ -423,6 +707,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -449,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( @@ -457,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, @@ -481,7 +817,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 NetworkAccessProfilePage(self._version, response) async def page_async( @@ -508,11 +850,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 065418f39d..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 @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class NetworkAccessProfileNetworkInstance(InstanceResource): - """ :ivar sid: The unique string that identifies the Network resource. :ivar network_access_profile_sid: The unique string that identifies the Network resource's Network Access Profile resource. @@ -48,13 +47,14 @@ def __init__( ) self.friendly_name: Optional[str] = payload.get("friendly_name") self.iso_country: Optional[str] = payload.get("iso_country") - self.identifiers: Optional[List[object]] = payload.get("identifiers") + self.identifiers: Optional[List[Dict[str, object]]] = payload.get("identifiers") self.url: Optional[str] = payload.get("url") self._solution = { "network_access_profile_sid": network_access_profile_sid, "sid": sid or self.sid, } + self._context: Optional[NetworkAccessProfileNetworkContext] = None @property @@ -91,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 @@ -109,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 @@ -122,6 +158,7 @@ def __repr__(self) -> str: class NetworkAccessProfileNetworkContext(InstanceContext): + def __init__(self, version: Version, network_access_profile_sid: str, sid: str): """ Initialize the NetworkAccessProfileNetworkContext @@ -143,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 @@ -150,9 +201,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -162,9 +235,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the NetworkAccessProfileNetworkInstance 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) -> NetworkAccessProfileNetworkInstance: @@ -174,18 +271,45 @@ def fetch(self) -> NetworkAccessProfileNetworkInstance: :returns: The fetched NetworkAccessProfileNetworkInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], ) - return NetworkAccessProfileNetworkInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the NetworkAccessProfileNetworkInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> NetworkAccessProfileNetworkInstance: """ @@ -194,18 +318,29 @@ async def fetch_async(self) -> NetworkAccessProfileNetworkInstance: :returns: The fetched NetworkAccessProfileNetworkInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return NetworkAccessProfileNetworkInstance( + self._version, + payload, + network_access_profile_sid=self._solution["network_access_profile_sid"], + sid=self._solution["sid"], ) - return NetworkAccessProfileNetworkInstance( + 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: """ @@ -220,6 +355,7 @@ def __repr__(self) -> str: class NetworkAccessProfileNetworkPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> NetworkAccessProfileNetworkInstance: @@ -228,6 +364,7 @@ def get_instance( :param payload: Payload response from the API """ + return NetworkAccessProfileNetworkInstance( self._version, payload, @@ -244,6 +381,7 @@ def __repr__(self) -> str: class NetworkAccessProfileNetworkList(ListResource): + def __init__(self, version: Version, network_access_profile_sid: str): """ Initialize the NetworkAccessProfileNetworkList @@ -264,58 +402,114 @@ 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 - - :param network: The SID of the Network resource to be added to the Network Access Profile resource. + Internal helper for create operation - :returns: The created NetworkAccessProfileNetworkInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Network": network, } ) + 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, + 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( { "Network": network, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -366,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, @@ -385,6 +629,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -411,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( @@ -419,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, @@ -443,8 +739,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + 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 NetworkAccessProfileNetworkPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -470,10 +774,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return NetworkAccessProfileNetworkPage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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: """ @@ -485,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: """ @@ -497,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 d9b00143ad..8b6f2a03a7 100644 --- a/twilio/rest/supersim/v1/settings_update.py +++ b/twilio/rest/supersim/v1/settings_update.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +24,7 @@ class SettingsUpdateInstance(InstanceResource): + class Status(object): SCHEDULED = "scheduled" IN_PROGRESS = "in-progress" @@ -48,7 +49,7 @@ def __init__(self, version: Version, payload: Dict[str, Any]): self.iccid: Optional[str] = payload.get("iccid") self.sim_sid: Optional[str] = payload.get("sim_sid") self.status: Optional["SettingsUpdateInstance.Status"] = payload.get("status") - self.packages: Optional[List[object]] = payload.get("packages") + self.packages: Optional[List[Dict[str, object]]] = payload.get("packages") self.date_completed: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_completed") ) @@ -70,12 +71,14 @@ def __repr__(self) -> str: class SettingsUpdatePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SettingsUpdateInstance: """ Build an instance of SettingsUpdateInstance :param payload: Payload response from the API """ + return SettingsUpdateInstance(self._version, payload) def __repr__(self) -> str: @@ -88,6 +91,7 @@ def __repr__(self) -> str: class SettingsUpdateList(ListResource): + def __init__(self, version: Version): """ Initialize the SettingsUpdateList @@ -159,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, @@ -182,6 +246,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -214,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( @@ -224,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, @@ -254,7 +382,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SettingsUpdatePage(self._version, response) async def page_async( @@ -287,11 +421,97 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 fae9427497..16f0046e17 100644 --- a/twilio/rest/supersim/v1/sim/__init__.py +++ b/twilio/rest/supersim/v1/sim/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,6 +26,7 @@ class SimInstance(InstanceResource): + class Status(object): NEW = "new" READY = "ready" @@ -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: """ @@ -194,6 +274,7 @@ def __repr__(self) -> str: class SimContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SimContext @@ -212,6 +293,22 @@ def __init__(self, version: Version, sid: str): self._billing_periods: Optional[BillingPeriodList] = None self._sim_ip_addresses: Optional[SimIpAddressList] = None + 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) -> SimInstance: """ Fetch the SimInstance @@ -219,17 +316,43 @@ def fetch(self) -> SimInstance: :returns: The fetched SimInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SimInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SimInstance: """ @@ -238,17 +361,63 @@ async def fetch_async(self) -> SimInstance: :returns: The fetched SimInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SimInstance( + 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, + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "Status": status, + "Fleet": fleet, + "CallbackUrl": callback_url, + "CallbackMethod": callback_method, + "AccountSid": account_sid, + } + ) + 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, @@ -271,6 +440,64 @@ def update( :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( { "UniqueName": unique_name, @@ -281,14 +508,15 @@ def update( "AccountSid": account_sid, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SimInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -311,24 +539,47 @@ async def update_async( :returns: The updated SimInstance """ - data = values.of( - { - "UniqueName": unique_name, - "Status": status, - "Fleet": fleet, - "CallbackUrl": callback_url, - "CallbackMethod": callback_method, - "AccountSid": account_sid, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return SimInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -365,12 +616,14 @@ def __repr__(self) -> str: class SimPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: """ Build an instance of SimInstance :param payload: Payload response from the API """ + return SimInstance(self._version, payload) def __repr__(self) -> str: @@ -383,6 +636,7 @@ def __repr__(self) -> str: class SimList(ListResource): + def __init__(self, version: Version): """ Initialize the SimList @@ -394,54 +648,112 @@ 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( { "Iccid": iccid, "RegistrationCode": registration_code, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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( { "Iccid": iccid, "RegistrationCode": registration_code, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -508,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, @@ -533,6 +909,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -568,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( @@ -579,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, @@ -612,7 +1058,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SimPage(self._version, response) async def page_async( @@ -648,11 +1100,103 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 52afd38c70..90a0e13d3d 100644 --- a/twilio/rest/supersim/v1/sim/billing_period.py +++ b/twilio/rest/supersim/v1/sim/billing_period.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +24,7 @@ class BillingPeriodInstance(InstanceResource): + class BpType(object): READY = "ready" ACTIVE = "active" @@ -76,12 +77,14 @@ def __repr__(self) -> str: class BillingPeriodPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BillingPeriodInstance: """ Build an instance of BillingPeriodInstance :param payload: Payload response from the API """ + return BillingPeriodInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -96,6 +99,7 @@ def __repr__(self) -> str: class BillingPeriodList(ListResource): + def __init__(self, version: Version, sim_sid: str): """ Initialize the BillingPeriodList @@ -162,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, @@ -181,6 +235,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -207,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( @@ -215,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, @@ -239,8 +345,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return BillingPeriodPage(self._version, response, self._solution) + 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 BillingPeriodPage(self._version, response, solution=self._solution) async def page_async( self, @@ -266,10 +378,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return BillingPeriodPage(self._version, response, self._solution) + 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: """ @@ -281,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: """ @@ -293,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 42911d1372..9d67476a36 100644 --- a/twilio/rest/supersim/v1/sim/sim_ip_address.py +++ b/twilio/rest/supersim/v1/sim/sim_ip_address.py @@ -12,9 +12,9 @@ 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 @@ -23,6 +23,7 @@ class SimIpAddressInstance(InstanceResource): + class IpAddressVersion(object): IPV4 = "IPv4" IPV6 = "IPv6" @@ -36,9 +37,9 @@ def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): super().__init__(version) self.ip_address: Optional[str] = payload.get("ip_address") - self.ip_address_version: Optional[ - "SimIpAddressInstance.IpAddressVersion" - ] = payload.get("ip_address_version") + self.ip_address_version: Optional["SimIpAddressInstance.IpAddressVersion"] = ( + payload.get("ip_address_version") + ) self._solution = { "sim_sid": sim_sid, @@ -55,12 +56,14 @@ def __repr__(self) -> str: class SimIpAddressPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SimIpAddressInstance: """ Build an instance of SimIpAddressInstance :param payload: Payload response from the API """ + return SimIpAddressInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -75,6 +78,7 @@ def __repr__(self) -> str: class SimIpAddressList(ListResource): + def __init__(self, version: Version, sim_sid: str): """ Initialize the SimIpAddressList @@ -141,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, @@ -160,6 +214,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -186,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( @@ -194,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, @@ -218,8 +324,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SimIpAddressPage(self._version, response, self._solution) + 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 SimIpAddressPage(self._version, response, solution=self._solution) async def page_async( self, @@ -245,10 +357,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SimIpAddressPage(self._version, response, self._solution) + 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: """ @@ -260,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: """ @@ -272,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 83601dd7ce..3b4ce6558d 100644 --- a/twilio/rest/supersim/v1/sms_command.py +++ b/twilio/rest/supersim/v1/sms_command.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class SmsCommandInstance(InstanceResource): + class Direction(object): TO_SIM = "to_sim" FROM_SIM = "from_sim" @@ -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 @@ -117,6 +137,7 @@ def __repr__(self) -> str: class SmsCommandContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SmsCommandContext @@ -132,6 +153,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/SmsCommands/{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) -> SmsCommandInstance: """ Fetch the SmsCommandInstance @@ -139,17 +176,43 @@ def fetch(self) -> SmsCommandInstance: :returns: The fetched SmsCommandInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SmsCommandInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SmsCommandInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SmsCommandInstance: """ @@ -158,17 +221,27 @@ async def fetch_async(self) -> SmsCommandInstance: :returns: The fetched SmsCommandInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SmsCommandInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SmsCommandInstance( + 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: """ @@ -181,12 +254,14 @@ def __repr__(self) -> str: class SmsCommandPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SmsCommandInstance: """ Build an instance of SmsCommandInstance :param payload: Payload response from the API """ + return SmsCommandInstance(self._version, payload) def __repr__(self) -> str: @@ -199,6 +274,7 @@ def __repr__(self) -> str: class SmsCommandList(ListResource): + def __init__(self, version: Version): """ Initialize the SmsCommandList @@ -210,6 +286,38 @@ def __init__(self, version: Version): self._uri = "/SmsCommands" + def _create( + self, + sim: str, + payload: str, + callback_method: Union[str, object] = values.unset, + callback_url: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Sim": sim, + "Payload": payload, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + } + ) + 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, sim: str, @@ -227,6 +335,54 @@ def create( :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( { "Sim": sim, @@ -235,14 +391,15 @@ def create( "CallbackUrl": callback_url, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SmsCommandInstance(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, @@ -261,22 +418,39 @@ async def create_async( :returns: The created SmsCommandInstance """ - data = values.of( - { - "Sim": sim, - "Payload": payload, - "CallbackMethod": callback_method, - "CallbackUrl": callback_url, - } + payload, _, _ = await self._create_async( + sim=sim, + payload=payload, + callback_method=callback_method, + callback_url=callback_url, ) + return SmsCommandInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return SmsCommandInstance(self._version, payload) + :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, @@ -344,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, @@ -369,6 +607,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -404,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( @@ -415,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, @@ -448,7 +756,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SmsCommandPage(self._version, response) async def page_async( @@ -484,11 +798,103 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 5962a59951..05547f6d64 100644 --- a/twilio/rest/supersim/v1/usage_record.py +++ b/twilio/rest/supersim/v1/usage_record.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,6 +24,7 @@ class UsageRecordInstance(InstanceResource): + class Granularity(object): HOUR = "hour" DAY = "day" @@ -77,12 +78,14 @@ def __repr__(self) -> str: class UsageRecordPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: """ Build an instance of UsageRecordInstance :param payload: Payload response from the API """ + return UsageRecordInstance(self._version, payload) def __repr__(self) -> str: @@ -95,6 +98,7 @@ def __repr__(self) -> str: class UsageRecordList(ListResource): + def __init__(self, version: Version): """ Initialize the UsageRecordList @@ -208,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, @@ -243,6 +347,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -293,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( @@ -309,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, @@ -357,7 +561,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 UsageRecordPage(self._version, response) async def page_async( @@ -408,11 +618,133 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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/SyncBase.py b/twilio/rest/sync/SyncBase.py index 35c4fa9846..113cac0390 100644 --- a/twilio/rest/sync/SyncBase.py +++ b/twilio/rest/sync/SyncBase.py @@ -17,6 +17,7 @@ class SyncBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Sync Domain diff --git a/twilio/rest/sync/v1/__init__.py b/twilio/rest/sync/v1/__init__.py index db6c478992..e98201bd41 100644 --- a/twilio/rest/sync/v1/__init__.py +++ b/twilio/rest/sync/v1/__init__.py @@ -19,6 +19,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Sync diff --git a/twilio/rest/sync/v1/service/__init__.py b/twilio/rest/sync/v1/service/__init__.py index 7db062b90d..a376ed7982 100644 --- a/twilio/rest/sync/v1/service/__init__.py +++ b/twilio/rest/sync/v1/service/__init__.py @@ -12,10 +12,10 @@ 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 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,7 +28,6 @@ class ServiceInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Service 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. It is a read-only property, it cannot be assigned using REST API. @@ -81,6 +80,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -116,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 @@ -134,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, @@ -200,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: """ @@ -239,6 +341,7 @@ def __repr__(self) -> str: class ServiceContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ServiceContext @@ -259,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 @@ -266,9 +383,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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: @@ -278,9 +417,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -290,17 +453,43 @@ def fetch(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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: """ @@ -309,17 +498,71 @@ async def fetch_async(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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, + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "WebhookUrl": webhook_url, + "FriendlyName": friendly_name, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_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, @@ -344,25 +587,95 @@ def update( :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( { "WebhookUrl": webhook_url, "FriendlyName": friendly_name, - "ReachabilityWebhooksEnabled": reachability_webhooks_enabled, - "AclEnabled": acl_enabled, - "ReachabilityDebouncingEnabled": reachability_debouncing_enabled, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), "ReachabilityDebouncingWindow": reachability_debouncing_window, - "WebhooksFromRestEnabled": webhooks_from_rest_enabled, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -387,25 +700,51 @@ async def update_async( :returns: The updated ServiceInstance """ - data = values.of( - { - "WebhookUrl": webhook_url, - "FriendlyName": friendly_name, - "ReachabilityWebhooksEnabled": reachability_webhooks_enabled, - "AclEnabled": acl_enabled, - "ReachabilityDebouncingEnabled": reachability_debouncing_enabled, - "ReachabilityDebouncingWindow": reachability_debouncing_window, - "WebhooksFromRestEnabled": webhooks_from_rest_enabled, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + :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: @@ -466,12 +805,14 @@ def __repr__(self) -> str: 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: @@ -484,6 +825,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -495,6 +837,50 @@ def __init__(self, version: 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, + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "WebhookUrl": webhook_url, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), + "ReachabilityDebouncingWindow": reachability_debouncing_window, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_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, @@ -518,25 +904,95 @@ def create( :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( { "FriendlyName": friendly_name, "WebhookUrl": webhook_url, - "ReachabilityWebhooksEnabled": reachability_webhooks_enabled, - "AclEnabled": acl_enabled, - "ReachabilityDebouncingEnabled": reachability_debouncing_enabled, + "ReachabilityWebhooksEnabled": serialize.boolean_to_string( + reachability_webhooks_enabled + ), + "AclEnabled": serialize.boolean_to_string(acl_enabled), + "ReachabilityDebouncingEnabled": serialize.boolean_to_string( + reachability_debouncing_enabled + ), "ReachabilityDebouncingWindow": reachability_debouncing_window, - "WebhooksFromRestEnabled": webhooks_from_rest_enabled, + "WebhooksFromRestEnabled": serialize.boolean_to_string( + webhooks_from_rest_enabled + ), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(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, @@ -561,25 +1017,51 @@ async def create_async( :returns: The created ServiceInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "WebhookUrl": webhook_url, - "ReachabilityWebhooksEnabled": reachability_webhooks_enabled, - "AclEnabled": acl_enabled, - "ReachabilityDebouncingEnabled": reachability_debouncing_enabled, - "ReachabilityDebouncingWindow": reachability_debouncing_window, - "WebhooksFromRestEnabled": webhooks_from_rest_enabled, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return ServiceInstance(self._version, payload) + :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, @@ -631,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, @@ -650,6 +1182,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -676,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( @@ -684,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, @@ -708,7 +1292,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -735,11 +1325,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 5689594a8a..3611fe0d18 100644 --- a/twilio/rest/sync/v1/service/document/__init__.py +++ b/twilio/rest/sync/v1/service/document/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class DocumentInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Document 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 and can be up to 320 characters long. @@ -75,6 +74,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[DocumentContext] = None @property @@ -111,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 @@ -129,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, @@ -171,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: """ @@ -189,6 +267,7 @@ def __repr__(self) -> str: class DocumentContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the DocumentContext @@ -208,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 @@ -215,9 +308,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -227,9 +342,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentInstance 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) -> DocumentInstance: @@ -239,18 +378,45 @@ def fetch(self) -> DocumentInstance: :returns: The fetched DocumentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return DocumentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DocumentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> DocumentInstance: """ @@ -259,50 +425,80 @@ async def fetch_async(self) -> DocumentInstance: :returns: The fetched DocumentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return DocumentInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return DocumentInstance( + 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( + 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 + Internal helper for update operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "Data": serialize.object(data), "Ttl": ttl, } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + headers = values.of({}) - payload = self._version.update( + 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, + 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, @@ -310,37 +506,82 @@ 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( { "Data": serialize.object(data), "Ttl": ttl, } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + 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" - payload = await self._version.update_async( + 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, + 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, @@ -348,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: """ @@ -372,12 +639,14 @@ def __repr__(self) -> str: 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"] ) @@ -392,6 +661,7 @@ def __repr__(self) -> str: class DocumentList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the DocumentList @@ -408,6 +678,36 @@ def __init__(self, version: Version, service_sid: str): } 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, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "Data": serialize.object(data), + "Ttl": ttl, + } + ) + 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, unique_name: Union[str, object] = values.unset, @@ -423,6 +723,47 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "UniqueName": unique_name, @@ -430,15 +771,14 @@ def create( "Ttl": ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return DocumentInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -456,23 +796,35 @@ async def create_async( :returns: The created DocumentInstance """ - data = values.of( - { - "UniqueName": unique_name, - "Data": serialize.object(data), - "Ttl": ttl, - } + payload, _, _ = await self._create_async( + unique_name=unique_name, data=data, ttl=ttl ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return DocumentInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return DocumentInstance( + 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, @@ -524,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, @@ -543,6 +945,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -569,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( @@ -577,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, @@ -601,8 +1055,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DocumentPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -628,10 +1088,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return DocumentPage(self._version, response, self._solution) + 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: """ @@ -643,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: """ @@ -655,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 da0241f552..16f87b9cd1 100644 --- a/twilio/rest/sync/v1/service/document/document_permission.py +++ b/twilio/rest/sync/v1/service/document/document_permission.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import values +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 @@ -23,7 +23,6 @@ class DocumentPermissionInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Document Permission resource. :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. @@ -59,6 +58,7 @@ def __init__( "document_sid": document_sid, "identity": identity or self.identity, } + self._context: Optional[DocumentPermissionContext] = None @property @@ -96,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 @@ -114,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": @@ -150,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 @@ -161,6 +233,7 @@ def __repr__(self) -> str: class DocumentPermissionContext(InstanceContext): + def __init__( self, version: Version, service_sid: str, document_sid: str, identity: str ): @@ -184,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 @@ -191,9 +278,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -203,9 +312,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the DocumentPermissionInstance 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) -> DocumentPermissionInstance: @@ -215,19 +348,47 @@ def fetch(self) -> DocumentPermissionInstance: :returns: The fetched DocumentPermissionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], ) - return DocumentPermissionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the DocumentPermissionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> DocumentPermissionInstance: """ @@ -236,19 +397,56 @@ async def fetch_async(self) -> DocumentPermissionInstance: :returns: The fetched DocumentPermissionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], ) - return DocumentPermissionInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the DocumentPermissionInstance and return response metadata + + + :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( + { + "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" + + 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 @@ -262,27 +460,63 @@ def update( :returns: The updated DocumentPermissionInstance """ - data = values.of( - { - "Read": read, - "Write": write, - "Manage": manage, - } + payload, _, _ = self._update(read=read, write=write, manage=manage) + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], ) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the DocumentPermissionInstance and return response metadata - return 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: 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( + { + "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" + + 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 @@ -296,27 +530,38 @@ async def update_async( :returns: The updated DocumentPermissionInstance """ - data = values.of( - { - "Read": read, - "Write": write, - "Manage": manage, - } + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) + return DocumentPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + document_sid=self._solution["document_sid"], + identity=self._solution["identity"], ) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return 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: 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: """ @@ -329,12 +574,14 @@ def __repr__(self) -> str: 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, @@ -352,6 +599,7 @@ def __repr__(self) -> str: class DocumentPermissionList(ListResource): + def __init__(self, version: Version, service_sid: str, document_sid: str): """ Initialize the DocumentPermissionList @@ -424,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, @@ -443,6 +741,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -469,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( @@ -477,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, @@ -501,8 +851,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DocumentPermissionPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -528,10 +884,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return DocumentPermissionPage(self._version, response, self._solution) + 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: """ @@ -543,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: """ @@ -555,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 545ebee389..e757173ab9 100644 --- a/twilio/rest/sync/v1/service/sync_list/__init__.py +++ b/twilio/rest/sync/v1/service/sync_list/__init__.py @@ -12,10 +12,10 @@ 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 @@ -28,7 +28,6 @@ class SyncListInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Sync List 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. @@ -74,6 +73,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SyncListContext] = None @property @@ -110,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 @@ -128,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, @@ -164,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: """ @@ -189,6 +261,7 @@ def __repr__(self) -> str: class SyncListContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the SyncListContext @@ -209,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 @@ -216,9 +303,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -228,9 +337,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListInstance 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) -> SyncListInstance: @@ -240,18 +373,45 @@ def fetch(self) -> SyncListInstance: :returns: The fetched SyncListInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return SyncListInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SyncListInstance: """ @@ -260,45 +420,72 @@ async def fetch_async(self) -> SyncListInstance: :returns: The fetched SyncListInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SyncListInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return SyncListInstance( + 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( + def _update( self, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncListInstance: + ) -> tuple: """ - 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. + Internal helper for update operation - :returns: The updated SyncListInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Ttl": ttl, "CollectionTtl": collection_ttl, } ) + 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, + 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, @@ -306,32 +493,72 @@ 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( { "Ttl": ttl, "CollectionTtl": collection_ttl, } ) + 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, + 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, @@ -339,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: """ @@ -376,12 +627,14 @@ def __repr__(self) -> str: 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"] ) @@ -396,6 +649,7 @@ def __repr__(self) -> str: class SyncListList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the SyncListList @@ -412,6 +666,36 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Lists".format(**self._solution) + def _create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + 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, unique_name: Union[str, object] = values.unset, @@ -427,6 +711,49 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "UniqueName": unique_name, @@ -434,15 +761,14 @@ def create( "CollectionTtl": collection_ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SyncListInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -460,23 +786,35 @@ async def create_async( :returns: The created SyncListInstance """ - data = values.of( - { - "UniqueName": unique_name, - "Ttl": ttl, - "CollectionTtl": collection_ttl, - } + payload, _, _ = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return SyncListInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return SyncListInstance( + 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, @@ -528,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, @@ -547,6 +935,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -573,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( @@ -581,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, @@ -605,8 +1045,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SyncListPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -632,10 +1078,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SyncListPage(self._version, response, self._solution) + 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: """ @@ -647,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: """ @@ -659,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 640b4c38ce..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 @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class SyncListItemInstance(InstanceResource): + class QueryFromBoundType(object): INCLUSIVE = "inclusive" EXCLUSIVE = "exclusive" @@ -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 @@ -205,6 +307,7 @@ def __repr__(self) -> str: class SyncListItemContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, list_sid: str, index: int): """ Initialize the SyncListItemContext @@ -226,6 +329,25 @@ 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ Deletes the SyncListItemInstance @@ -234,13 +356,40 @@ def delete(self, if_match: Union[str, object] = values.unset) -> bool: :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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, if_match: Union[str, object] = values.unset) -> bool: """ @@ -250,14 +399,36 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "If-Match": if_match, - } - ) + success, _, _ = await self._delete_async(if_match=if_match) + return success - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch(self) -> SyncListItemInstance: @@ -267,19 +438,47 @@ def fetch(self) -> SyncListItemInstance: :returns: The fetched SyncListItemInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], ) - return SyncListItemInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListItemInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SyncListItemInstance: """ @@ -288,39 +487,47 @@ async def fetch_async(self) -> SyncListItemInstance: :returns: The fetched SyncListItemInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SyncListItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + index=self._solution["index"], ) - return SyncListItemInstance( + 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( + 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( { "Data": serialize.object(data), @@ -329,16 +536,47 @@ def update( "CollectionTtl": collection_ttl, } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + 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" - payload = self._version.update( + 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, + 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, @@ -347,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. @@ -364,8 +602,39 @@ 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( { "Data": serialize.object(data), @@ -374,16 +643,47 @@ async def update_async( "CollectionTtl": collection_ttl, } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + 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" - payload = await self._version.update_async( + 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, + 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, @@ -392,8 +692,43 @@ async def update_async( index=self._solution["index"], ) - def __repr__(self) -> str: - """ + 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: + """ Provide a friendly representation :returns: Machine friendly representation @@ -403,12 +738,14 @@ def __repr__(self) -> str: 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, @@ -426,6 +763,7 @@ def __repr__(self) -> str: class SyncListItemList(ListResource): + def __init__(self, version: Version, service_sid: str, list_sid: str): """ Initialize the SyncListItemList @@ -446,23 +784,20 @@ 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( { "Data": serialize.object(data), @@ -471,13 +806,36 @@ def create( "CollectionTtl": collection_ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -485,23 +843,48 @@ 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( { "Data": serialize.object(data), @@ -510,13 +893,36 @@ async def create_async( "CollectionTtl": collection_ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -524,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, @@ -590,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, @@ -615,6 +1113,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -650,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( @@ -661,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, @@ -694,8 +1262,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SyncListItemPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -730,10 +1304,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SyncListItemPage(self._version, response, self._solution) + 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: """ @@ -745,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: """ @@ -757,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 f0d970b18d..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 @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import values +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 @@ -23,7 +23,6 @@ class SyncListPermissionInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync List Permission resource. :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. @@ -59,6 +58,7 @@ def __init__( "list_sid": list_sid, "identity": identity or self.identity, } + self._context: Optional[SyncListPermissionContext] = None @property @@ -96,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 @@ -114,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": @@ -150,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 @@ -161,6 +233,7 @@ def __repr__(self) -> str: class SyncListPermissionContext(InstanceContext): + def __init__( self, version: Version, service_sid: str, list_sid: str, identity: str ): @@ -186,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 @@ -193,9 +280,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -205,9 +314,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncListPermissionInstance 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) -> SyncListPermissionInstance: @@ -217,19 +350,47 @@ def fetch(self) -> SyncListPermissionInstance: :returns: The fetched SyncListPermissionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - return SyncListPermissionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncListPermissionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SyncListPermissionInstance: """ @@ -238,19 +399,56 @@ async def fetch_async(self) -> SyncListPermissionInstance: :returns: The fetched SyncListPermissionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - return SyncListPermissionInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncListPermissionInstance and return response metadata + + + :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( + { + "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" + + 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 @@ -264,27 +462,63 @@ def update( :returns: The updated SyncListPermissionInstance """ - data = values.of( - { - "Read": read, - "Write": write, - "Manage": manage, - } + payload, _, _ = self._update(read=read, write=write, manage=manage) + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncListPermissionInstance and return response metadata - return 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: 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( + { + "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" + + 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 @@ -298,27 +532,38 @@ async def update_async( :returns: The updated SyncListPermissionInstance """ - data = values.of( - { - "Read": read, - "Write": write, - "Manage": manage, - } + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) + return SyncListPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + list_sid=self._solution["list_sid"], + identity=self._solution["identity"], ) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return 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: 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: """ @@ -331,12 +576,14 @@ def __repr__(self) -> str: 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, @@ -354,6 +601,7 @@ def __repr__(self) -> str: class SyncListPermissionList(ListResource): + def __init__(self, version: Version, service_sid: str, list_sid: str): """ Initialize the SyncListPermissionList @@ -424,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, @@ -443,6 +741,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -469,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( @@ -477,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, @@ -501,8 +851,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SyncListPermissionPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -528,10 +884,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SyncListPermissionPage(self._version, response, self._solution) + 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: """ @@ -543,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: """ @@ -555,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 5b38378f2b..1c5049b798 100644 --- a/twilio/rest/sync/v1/service/sync_map/__init__.py +++ b/twilio/rest/sync/v1/service/sync_map/__init__.py @@ -12,10 +12,10 @@ 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 @@ -28,7 +28,6 @@ class SyncMapInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Sync Map 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. @@ -74,6 +73,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SyncMapContext] = None @property @@ -110,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 @@ -128,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, @@ -164,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: """ @@ -189,6 +261,7 @@ def __repr__(self) -> str: class SyncMapContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the SyncMapContext @@ -209,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 @@ -216,9 +303,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -228,9 +337,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapInstance 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) -> SyncMapInstance: @@ -240,18 +373,45 @@ def fetch(self) -> SyncMapInstance: :returns: The fetched SyncMapInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return SyncMapInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SyncMapInstance: """ @@ -260,45 +420,72 @@ async def fetch_async(self) -> SyncMapInstance: :returns: The fetched SyncMapInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SyncMapInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return SyncMapInstance( + 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( + def _update( self, ttl: Union[int, object] = values.unset, collection_ttl: Union[int, object] = values.unset, - ) -> SyncMapInstance: + ) -> tuple: """ - 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. + Internal helper for update operation - :returns: The updated SyncMapInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Ttl": ttl, "CollectionTtl": collection_ttl, } ) + 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, + 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, @@ -306,32 +493,72 @@ 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( { "Ttl": ttl, "CollectionTtl": collection_ttl, } ) + 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, + 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, @@ -339,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: """ @@ -376,12 +627,14 @@ def __repr__(self) -> str: 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"] ) @@ -396,6 +649,7 @@ def __repr__(self) -> str: class SyncMapList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the SyncMapList @@ -412,6 +666,36 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Maps".format(**self._solution) + def _create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + collection_ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + "CollectionTtl": collection_ttl, + } + ) + 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, unique_name: Union[str, object] = values.unset, @@ -427,6 +711,49 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "UniqueName": unique_name, @@ -434,15 +761,14 @@ def create( "CollectionTtl": collection_ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SyncMapInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -460,23 +786,35 @@ async def create_async( :returns: The created SyncMapInstance """ - data = values.of( - { - "UniqueName": unique_name, - "Ttl": ttl, - "CollectionTtl": collection_ttl, - } + payload, _, _ = await self._create_async( + unique_name=unique_name, ttl=ttl, collection_ttl=collection_ttl ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return SyncMapInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return SyncMapInstance( + 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, @@ -528,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, @@ -547,6 +935,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -573,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( @@ -581,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, @@ -605,8 +1045,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SyncMapPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -632,10 +1078,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SyncMapPage(self._version, response, self._solution) + 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: """ @@ -647,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: """ @@ -659,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 ef290caab2..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 @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class SyncMapItemInstance(InstanceResource): + class QueryFromBoundType(object): INCLUSIVE = "inclusive" EXCLUSIVE = "exclusive" @@ -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 @@ -205,6 +307,7 @@ def __repr__(self) -> str: class SyncMapItemContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, map_sid: str, key: str): """ Initialize the SyncMapItemContext @@ -226,6 +329,25 @@ 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ Deletes the SyncMapItemInstance @@ -234,13 +356,40 @@ def delete(self, if_match: Union[str, object] = values.unset) -> bool: :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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, if_match: Union[str, object] = values.unset) -> bool: """ @@ -250,14 +399,36 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "If-Match": if_match, - } - ) + success, _, _ = await self._delete_async(if_match=if_match) + return success - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch(self) -> SyncMapItemInstance: @@ -267,19 +438,47 @@ def fetch(self) -> SyncMapItemInstance: :returns: The fetched SyncMapItemInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], ) - return SyncMapItemInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapItemInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SyncMapItemInstance: """ @@ -288,39 +487,47 @@ async def fetch_async(self) -> SyncMapItemInstance: :returns: The fetched SyncMapItemInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SyncMapItemInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + key=self._solution["key"], ) - return SyncMapItemInstance( + 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( + 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 - - :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. + Internal helper for update operation - :returns: The updated SyncMapItemInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Data": serialize.object(data), @@ -329,16 +536,47 @@ def update( "CollectionTtl": collection_ttl, } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + 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" - payload = self._version.update( + 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, + 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, @@ -347,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. @@ -364,8 +602,39 @@ 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( { "Data": serialize.object(data), @@ -374,16 +643,47 @@ async def update_async( "CollectionTtl": collection_ttl, } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + 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" - payload = await self._version.update_async( + 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, + 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, @@ -392,8 +692,43 @@ async def update_async( key=self._solution["key"], ) - def __repr__(self) -> str: - """ + 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 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. + + :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 @@ -403,12 +738,14 @@ def __repr__(self) -> str: 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, @@ -426,6 +763,7 @@ def __repr__(self) -> str: class SyncMapItemList(ListResource): + def __init__(self, version: Version, service_sid: str, map_sid: str): """ Initialize the SyncMapItemList @@ -446,25 +784,21 @@ 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( { "Key": key, @@ -474,13 +808,42 @@ def create( "CollectionTtl": collection_ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -488,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. @@ -505,8 +868,38 @@ 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( { "Key": key, @@ -516,13 +909,42 @@ async def create_async( "CollectionTtl": collection_ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -530,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, @@ -596,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, @@ -621,6 +1141,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( order=order, @@ -656,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( @@ -667,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, @@ -700,8 +1290,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SyncMapItemPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -736,10 +1332,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SyncMapItemPage(self._version, response, self._solution) + 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: """ @@ -751,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: """ @@ -763,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 ee34694dd4..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 @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import values +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 @@ -23,7 +23,6 @@ class SyncMapPermissionInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Sync Map Permission resource. :ivar service_sid: The SID of the [Sync Service](https://www.twilio.com/docs/sync/api/service) the resource is associated with. @@ -59,6 +58,7 @@ def __init__( "map_sid": map_sid, "identity": identity or self.identity, } + self._context: Optional[SyncMapPermissionContext] = None @property @@ -96,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 @@ -114,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": @@ -150,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 @@ -161,6 +233,7 @@ def __repr__(self) -> str: class SyncMapPermissionContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, map_sid: str, identity: str): """ Initialize the SyncMapPermissionContext @@ -184,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 @@ -191,9 +278,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -203,9 +312,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncMapPermissionInstance 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) -> SyncMapPermissionInstance: @@ -215,19 +348,47 @@ def fetch(self) -> SyncMapPermissionInstance: :returns: The fetched SyncMapPermissionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - return SyncMapPermissionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncMapPermissionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SyncMapPermissionInstance: """ @@ -236,19 +397,56 @@ async def fetch_async(self) -> SyncMapPermissionInstance: :returns: The fetched SyncMapPermissionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - return SyncMapPermissionInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SyncMapPermissionInstance and return response metadata + + + :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( + { + "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" + + 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 @@ -262,27 +460,63 @@ def update( :returns: The updated SyncMapPermissionInstance """ - data = values.of( - { - "Read": read, - "Write": write, - "Manage": manage, - } + payload, _, _ = self._update(read=read, write=write, manage=manage) + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + def update_with_http_info( + self, read: bool, write: bool, manage: bool + ) -> ApiResponse: + """ + Update the SyncMapPermissionInstance and return response metadata - return 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: 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( + { + "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" + + 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 @@ -296,27 +530,38 @@ async def update_async( :returns: The updated SyncMapPermissionInstance """ - data = values.of( - { - "Read": read, - "Write": write, - "Manage": manage, - } + payload, _, _ = await self._update_async(read=read, write=write, manage=manage) + return SyncMapPermissionInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + map_sid=self._solution["map_sid"], + identity=self._solution["identity"], ) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return 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: 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: """ @@ -329,12 +574,14 @@ def __repr__(self) -> str: 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, @@ -352,6 +599,7 @@ def __repr__(self) -> str: class SyncMapPermissionList(ListResource): + def __init__(self, version: Version, service_sid: str, map_sid: str): """ Initialize the SyncMapPermissionList @@ -422,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, @@ -441,6 +739,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -467,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( @@ -475,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, @@ -499,8 +849,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SyncMapPermissionPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -526,10 +882,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SyncMapPermissionPage(self._version, response, self._solution) + 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: """ @@ -541,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: """ @@ -553,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 59507674dd..f233231d44 100644 --- a/twilio/rest/sync/v1/service/sync_stream/__init__.py +++ b/twilio/rest/sync/v1/service/sync_stream/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class SyncStreamInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Sync Stream 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. @@ -69,6 +68,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[SyncStreamContext] = None @property @@ -105,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 @@ -123,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 @@ -149,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: """ @@ -167,6 +231,7 @@ def __repr__(self) -> str: class SyncStreamContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the SyncStreamContext @@ -186,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 @@ -193,9 +272,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -205,9 +306,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SyncStreamInstance 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) -> SyncStreamInstance: @@ -217,18 +342,45 @@ def fetch(self) -> SyncStreamInstance: :returns: The fetched SyncStreamInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SyncStreamInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return SyncStreamInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SyncStreamInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SyncStreamInstance: """ @@ -237,12 +389,7 @@ async def fetch_async(self) -> SyncStreamInstance: :returns: The fetched SyncStreamInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return SyncStreamInstance( self._version, payload, @@ -250,26 +397,54 @@ 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( { "Ttl": ttl, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -277,28 +452,59 @@ 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( { "Ttl": ttl, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -306,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: """ @@ -330,12 +555,14 @@ def __repr__(self) -> str: class SyncStreamPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SyncStreamInstance: """ Build an instance of SyncStreamInstance :param payload: Payload response from the API """ + return SyncStreamInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -350,6 +577,7 @@ def __repr__(self) -> str: class SyncStreamList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the SyncStreamList @@ -366,6 +594,34 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Streams".format(**self._solution) + def _create( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "Ttl": ttl, + } + ) + 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, unique_name: Union[str, object] = values.unset, @@ -379,21 +635,56 @@ def create( :returns: The created SyncStreamInstance """ + payload, _, _ = self._create(unique_name=unique_name, ttl=ttl) + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, + unique_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> ApiResponse: + """ + 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 = 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( { "UniqueName": unique_name, "Ttl": ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SyncStreamInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -409,22 +700,31 @@ async def create_async( :returns: The created SyncStreamInstance """ - data = values.of( - { - "UniqueName": unique_name, - "Ttl": ttl, - } + payload, _, _ = await self._create_async(unique_name=unique_name, ttl=ttl) + return SyncStreamInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return 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: 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, @@ -476,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, @@ -495,6 +845,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -521,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( @@ -529,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, @@ -553,8 +955,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SyncStreamPage(self._version, response, self._solution) + 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 SyncStreamPage(self._version, response, solution=self._solution) async def page_async( self, @@ -580,10 +988,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SyncStreamPage(self._version, response, self._solution) + 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: """ @@ -595,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: """ @@ -607,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 5227bb076b..f7646d1936 100644 --- a/twilio/rest/sync/v1/service/sync_stream/stream_message.py +++ b/twilio/rest/sync/v1/service/sync_stream/stream_message.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - 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 @@ -22,7 +22,6 @@ class StreamMessageInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Stream Message resource. :ivar data: An arbitrary, schema-less object that contains the Stream Message body. Can be up to 4 KiB in length. @@ -56,6 +55,7 @@ def __repr__(self) -> str: class StreamMessageList(ListResource): + def __init__(self, version: Version, service_sid: str, stream_sid: str): """ Initialize the StreamMessageList @@ -76,26 +76,38 @@ 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( { "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, + 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, @@ -103,26 +115,55 @@ 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( { "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, + 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, @@ -130,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/TaskrouterBase.py b/twilio/rest/taskrouter/TaskrouterBase.py index ee7fbfd7e8..4bbbdb602e 100644 --- a/twilio/rest/taskrouter/TaskrouterBase.py +++ b/twilio/rest/taskrouter/TaskrouterBase.py @@ -17,6 +17,7 @@ class TaskrouterBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Taskrouter Domain diff --git a/twilio/rest/taskrouter/v1/__init__.py b/twilio/rest/taskrouter/v1/__init__.py index a331fb3497..a17eeccc2a 100644 --- a/twilio/rest/taskrouter/v1/__init__.py +++ b/twilio/rest/taskrouter/v1/__init__.py @@ -19,6 +19,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Taskrouter diff --git a/twilio/rest/taskrouter/v1/workspace/__init__.py b/twilio/rest/taskrouter/v1/workspace/__init__.py index 886ba65c93..5e857c3d0a 100644 --- a/twilio/rest/taskrouter/v1/workspace/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/__init__.py @@ -12,10 +12,10 @@ 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 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 @@ -40,6 +40,7 @@ class WorkspaceInstance(InstanceResource): + class QueueOrder(object): FIFO = "FIFO" LIFO = "LIFO" @@ -83,15 +84,16 @@ def __init__( self.sid: Optional[str] = payload.get("sid") self.timeout_activity_name: Optional[str] = payload.get("timeout_activity_name") self.timeout_activity_sid: Optional[str] = payload.get("timeout_activity_sid") - self.prioritize_queue_order: Optional[ - "WorkspaceInstance.QueueOrder" - ] = payload.get("prioritize_queue_order") + self.prioritize_queue_order: Optional["WorkspaceInstance.QueueOrder"] = ( + payload.get("prioritize_queue_order") + ) 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[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: """ @@ -296,6 +404,7 @@ def __repr__(self) -> str: class WorkspaceContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the WorkspaceContext @@ -322,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 @@ -329,9 +452,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -341,9 +486,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkspaceInstance 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) -> WorkspaceInstance: @@ -353,17 +522,43 @@ def fetch(self) -> WorkspaceInstance: :returns: The fetched WorkspaceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return WorkspaceInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkspaceInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WorkspaceInstance: """ @@ -372,17 +567,67 @@ async def fetch_async(self) -> WorkspaceInstance: :returns: The fetched WorkspaceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WorkspaceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return WorkspaceInstance( + 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, + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "DefaultActivitySid": default_activity_sid, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "FriendlyName": friendly_name, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "TimeoutActivitySid": timeout_activity_sid, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + 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, @@ -409,25 +654,93 @@ def update( :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( { "DefaultActivitySid": default_activity_sid, "EventCallbackUrl": event_callback_url, "EventsFilter": events_filter, "FriendlyName": friendly_name, - "MultiTaskEnabled": multi_task_enabled, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), "TimeoutActivitySid": timeout_activity_sid, "PrioritizeQueueOrder": prioritize_queue_order, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WorkspaceInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -454,33 +767,61 @@ async def update_async( :returns: The updated WorkspaceInstance """ - data = values.of( - { - "DefaultActivitySid": default_activity_sid, - "EventCallbackUrl": event_callback_url, - "EventsFilter": events_filter, - "FriendlyName": friendly_name, - "MultiTaskEnabled": multi_task_enabled, - "TimeoutActivitySid": timeout_activity_sid, - "PrioritizeQueueOrder": prioritize_queue_order, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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"]) - @property - def activities(self) -> ActivityList: - """ - Access the activities - """ - if self._activities is None: - self._activities = ActivityList( + 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"], ) @@ -605,12 +946,14 @@ def __repr__(self) -> str: class WorkspacePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> WorkspaceInstance: """ Build an instance of WorkspaceInstance :param payload: Payload response from the API """ + return WorkspaceInstance(self._version, payload) def __repr__(self) -> str: @@ -623,6 +966,7 @@ def __repr__(self) -> str: class WorkspaceList(ListResource): + def __init__(self, version: Version): """ Initialize the WorkspaceList @@ -634,6 +978,44 @@ def __init__(self, version: Version): self._uri = "/Workspaces" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventCallbackUrl": event_callback_url, + "EventsFilter": events_filter, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), + "Template": template, + "PrioritizeQueueOrder": prioritize_queue_order, + } + ) + 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, @@ -657,24 +1039,87 @@ def create( :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( { "FriendlyName": friendly_name, "EventCallbackUrl": event_callback_url, "EventsFilter": events_filter, - "MultiTaskEnabled": multi_task_enabled, + "MultiTaskEnabled": serialize.boolean_to_string(multi_task_enabled), "Template": template, "PrioritizeQueueOrder": prioritize_queue_order, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WorkspaceInstance(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, @@ -699,24 +1144,49 @@ async def create_async( :returns: The created WorkspaceInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "EventCallbackUrl": event_callback_url, - "EventsFilter": events_filter, - "MultiTaskEnabled": multi_task_enabled, - "Template": template, - "PrioritizeQueueOrder": prioritize_queue_order, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return WorkspaceInstance(self._version, payload) + :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, @@ -774,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, @@ -795,6 +1321,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -824,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( @@ -833,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, @@ -860,7 +1444,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 WorkspacePage(self._version, response) async def page_async( @@ -890,11 +1480,91 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 b233113d33..580948aa5c 100644 --- a/twilio/rest/taskrouter/v1/workspace/activity.py +++ b/twilio/rest/taskrouter/v1/workspace/activity.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class ActivityInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Activity resource. :ivar available: Whether the Worker is eligible to receive a Task when it occupies the Activity. A value of `true`, `1`, or `yes` indicates the Activity is available. All other values indicate that it is not. The value cannot be changed after the Activity is created. @@ -64,6 +63,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[ActivityContext] = None @property @@ -100,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 @@ -118,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": @@ -146,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 @@ -157,6 +221,7 @@ def __repr__(self) -> str: class ActivityContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the ActivityContext @@ -176,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 @@ -183,9 +262,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -195,9 +296,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ActivityInstance 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) -> ActivityInstance: @@ -207,18 +332,45 @@ def fetch(self) -> ActivityInstance: :returns: The fetched ActivityInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ActivityInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return ActivityInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ActivityInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ActivityInstance: """ @@ -227,12 +379,7 @@ async def fetch_async(self) -> ActivityInstance: :returns: The fetched ActivityInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return ActivityInstance( self._version, payload, @@ -240,28 +387,56 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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 + ) -> 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, @@ -269,28 +444,61 @@ 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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 + ) -> 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, @@ -298,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 @@ -309,12 +538,14 @@ def __repr__(self) -> str: class ActivityPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ActivityInstance: """ Build an instance of ActivityInstance :param payload: Payload response from the API """ + return ActivityInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -329,6 +560,7 @@ def __repr__(self) -> str: class ActivityList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the ActivityList @@ -345,6 +577,32 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Activities".format(**self._solution) + def _create( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Available": serialize.boolean_to_string(available), + } + ) + 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, available: Union[bool, object] = values.unset ) -> ActivityInstance: @@ -356,21 +614,54 @@ def create( :returns: The created ActivityInstance """ + payload, _, _ = self._create(friendly_name=friendly_name, available=available) + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] + ) + + def create_with_http_info( + self, friendly_name: str, available: Union[bool, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, - "Available": available, + "Available": serialize.boolean_to_string(available), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ActivityInstance( - self._version, payload, workspace_sid=self._solution["workspace_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( @@ -384,22 +675,31 @@ async def create_async( :returns: The created ActivityInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Available": available, - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, available=available ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return ActivityInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - return ActivityInstance( + 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, @@ -467,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, @@ -490,6 +854,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -522,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( @@ -532,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, @@ -562,8 +990,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ActivityPage(self._version, response, self._solution) + 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 ActivityPage(self._version, response, solution=self._solution) async def page_async( self, @@ -595,10 +1029,96 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ActivityPage(self._version, response, self._solution) + 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: """ @@ -610,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: """ @@ -622,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 82f71317e2..73cc6f2ebf 100644 --- a/twilio/rest/taskrouter/v1/workspace/event.py +++ b/twilio/rest/taskrouter/v1/workspace/event.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ 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 resource that triggered the event. @@ -78,6 +77,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[EventContext] = None @property @@ -114,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 @@ -125,6 +143,7 @@ def __repr__(self) -> str: class EventContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the EventContext @@ -142,6 +161,22 @@ def __init__(self, version: Version, workspace_sid: str, sid: str): } self._uri = "/Workspaces/{workspace_sid}/Events/{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) -> EventInstance: """ Fetch the EventInstance @@ -149,18 +184,45 @@ def fetch(self) -> EventInstance: :returns: The fetched EventInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return EventInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EventInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EventInstance: """ @@ -169,18 +231,29 @@ async def fetch_async(self) -> EventInstance: :returns: The fetched EventInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EventInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return EventInstance( + 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: """ @@ -193,12 +266,14 @@ def __repr__(self) -> str: class EventPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EventInstance: """ Build an instance of EventInstance :param payload: Payload response from the API """ + return EventInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -213,6 +288,7 @@ def __repr__(self) -> str: class EventList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the EventList @@ -349,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, @@ -390,6 +584,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end_date=end_date, @@ -449,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( @@ -468,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, @@ -525,8 +837,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return EventPage(self._version, response, self._solution) + 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 EventPage(self._version, response, solution=self._solution) async def page_async( self, @@ -585,10 +903,150 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return EventPage(self._version, response, self._solution) + 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: """ @@ -600,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: """ @@ -612,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 5b9ed673ac..c03fe1abb9 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,6 +25,7 @@ class TaskInstance(InstanceResource): + class Status(object): PENDING = "pending" RESERVED = "reserved" @@ -38,7 +39,7 @@ class Status(object): :ivar age: The number of seconds since the Task was created. :ivar assignment_status: :ivar attributes: The JSON string with custom attributes of the work. **Note** If this property has been assigned a value, it will only be displayed in FETCH action that returns a single resource. Otherwise, it will be null. - :ivar addons: An object that contains the [addon](https://www.twilio.com/docs/taskrouter/marketplace) data for all installed addons. + :ivar addons: An object that contains the [Add-on](https://www.twilio.com/docs/add-ons) data for all installed Add-ons. :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 task_queue_entered_date: The date and time in GMT when the Task entered the TaskQueue, specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. @@ -55,6 +56,9 @@ class Status(object): :ivar workspace_sid: The SID of the Workspace that contains the Task. :ivar url: The absolute URL of the Task resource. :ivar links: The URLs of related resources. + :ivar virtual_start_time: The date and time in GMT indicating the ordering for routing of the Task specified in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. + :ivar 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. + :ivar routing_target: A SID of a Worker, Queue, or Workflow to route a Task to """ def __init__( @@ -101,11 +105,17 @@ def __init__( self.workspace_sid: Optional[str] = payload.get("workspace_sid") self.url: Optional[str] = payload.get("url") self.links: Optional[Dict[str, object]] = payload.get("links") + self.virtual_start_time: Optional[datetime] = deserialize.iso8601_datetime( + payload.get("virtual_start_time") + ) + self.ignore_capacity: Optional[bool] = payload.get("ignore_capacity") + self.routing_target: Optional[str] = payload.get("routing_target") self._solution = { "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[TaskContext] = None @property @@ -148,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 @@ -166,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, @@ -174,6 +230,7 @@ def update( 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 @@ -184,6 +241,7 @@ def update( :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 """ @@ -194,6 +252,7 @@ def update( reason=reason, priority=priority, task_channel=task_channel, + virtual_start_time=virtual_start_time, ) async def update_async( @@ -204,6 +263,7 @@ async def update_async( 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": """ Asynchronous coroutine to update the TaskInstance @@ -214,6 +274,7 @@ async def update_async( :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 """ @@ -224,6 +285,73 @@ async def update_async( reason=reason, priority=priority, task_channel=task_channel, + 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 @@ -244,6 +372,7 @@ def __repr__(self) -> str: class TaskContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the TaskContext @@ -263,6 +392,25 @@ 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ Deletes the TaskInstance @@ -271,13 +419,40 @@ def delete(self, if_match: Union[str, object] = values.unset) -> bool: :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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, if_match: Union[str, object] = values.unset) -> bool: """ @@ -287,14 +462,36 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "If-Match": if_match, - } - ) + success, _, _ = await self._delete_async(if_match=if_match) + return success - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch(self) -> TaskInstance: @@ -304,18 +501,45 @@ def fetch(self) -> TaskInstance: :returns: The fetched TaskInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return TaskInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TaskInstance: """ @@ -324,20 +548,31 @@ async def fetch_async(self) -> TaskInstance: :returns: The fetched TaskInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TaskInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return TaskInstance( + 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( + def _update( self, if_match: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, @@ -345,19 +580,15 @@ def update( reason: Union[str, object] = values.unset, priority: Union[int, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> TaskInstance: + virtual_start_time: Union[datetime, object] = values.unset, + ) -> 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`. + Internal helper for update operation - :returns: The updated TaskInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Attributes": attributes, @@ -365,18 +596,56 @@ def update( "Reason": reason, "Priority": priority, "TaskChannel": task_channel, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + headers = values.of({}) - payload = self._version.update( + 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, + 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, @@ -384,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, @@ -392,9 +661,10 @@ async def update_async( reason: Union[str, object] = values.unset, priority: Union[int, object] = values.unset, task_channel: Union[str, object] = values.unset, - ) -> TaskInstance: + virtual_start_time: Union[datetime, object] = values.unset, + ) -> 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. @@ -402,9 +672,44 @@ async def update_async( :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 + :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( { "Attributes": attributes, @@ -412,24 +717,102 @@ async def update_async( "Reason": reason, "Priority": priority, "TaskChannel": task_channel, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), } ) - headers = values.of( - { - "If-Match": if_match, - } - ) + headers = values.of({}) - payload = await self._version.update_async( + 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 ) - return TaskInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], - sid=self._solution["sid"], - ) + 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: + """ + 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: @@ -455,12 +838,14 @@ def __repr__(self) -> str: class TaskPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TaskInstance: """ Build an instance of TaskInstance :param payload: Payload response from the API """ + return TaskInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -475,6 +860,7 @@ def __repr__(self) -> str: class TaskList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the TaskList @@ -491,25 +877,25 @@ 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, task_channel: Union[str, object] = values.unset, workflow_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> TaskInstance: + 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: """ - 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 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\\\" }`. + Internal helper for create operation - :returns: The created TaskInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Timeout": timeout, @@ -517,38 +903,126 @@ def create( "TaskChannel": task_channel, "WorkflowSid": workflow_sid, "Attributes": attributes, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + "RoutingTarget": routing_target, + "IgnoreCapacity": ignore_capacity, + "TaskQueueSid": task_queue_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, + 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, task_channel: Union[str, object] = values.unset, workflow_sid: Union[str, object] = values.unset, attributes: Union[str, object] = values.unset, - ) -> TaskInstance: + 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 + 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( { "Timeout": timeout, @@ -556,19 +1030,107 @@ async def create_async( "TaskChannel": task_channel, "WorkflowSid": workflow_sid, "Attributes": attributes, + "VirtualStartTime": serialize.iso8601_datetime(virtual_start_time), + "RoutingTarget": routing_target, + "IgnoreCapacity": ignore_capacity, + "TaskQueueSid": task_queue_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -578,6 +1140,7 @@ def stream( 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, @@ -596,8 +1159,9 @@ def stream( :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 ordering: How to order the returned Task resources. y default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `Priority` or `DateCreated` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Multiple 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. - :param bool has_addons: Whether to read Tasks with addons. If `true`, returns only Tasks with addons. If `false`, returns only Tasks without addons. + :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 @@ -616,6 +1180,7 @@ def stream( 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"], @@ -632,6 +1197,7 @@ async def stream_async( 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, @@ -650,8 +1216,9 @@ async def stream_async( :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 ordering: How to order the returned Task resources. y default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `Priority` or `DateCreated` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Multiple 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. - :param bool has_addons: Whether to read Tasks with addons. If `true`, returns only Tasks with addons. If `false`, returns only Tasks without addons. + :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 @@ -670,6 +1237,7 @@ async def stream_async( 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"], @@ -677,6 +1245,118 @@ async def stream_async( return self._version.stream_async(page, limits["limit"]) + def stream_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, + ) -> tuple: + """ + 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`. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = self.page_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, + page_size=limits["page_size"], + ) + + generator = self._version.stream(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + + async def stream_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, + ) -> tuple: + """ + 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`. + :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: tuple of (generator, status_code, headers) where generator yields instances + """ + limits = self._version.read_limits(limit, page_size) + page_response = await self.page_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, + page_size=limits["page_size"], + ) + + generator = self._version.stream_async(page_response.data, limits["limit"]) + return (generator, page_response.status_code, page_response.headers) + def list( self, priority: Union[int, object] = values.unset, @@ -686,6 +1366,7 @@ def list( 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, @@ -703,8 +1384,9 @@ def list( :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 ordering: How to order the returned Task resources. y default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `Priority` or `DateCreated` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Multiple 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. - :param bool has_addons: Whether to read Tasks with addons. If `true`, returns only Tasks with addons. If `false`, returns only Tasks without addons. + :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 @@ -714,6 +1396,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( priority=priority, @@ -723,6 +1406,7 @@ def list( 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, @@ -739,6 +1423,7 @@ async def list_async( 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, @@ -756,8 +1441,9 @@ async def list_async( :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 ordering: How to order the returned Task resources. y default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `Priority` or `DateCreated` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Multiple 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. - :param bool has_addons: Whether to read Tasks with addons. If `true`, returns only Tasks with addons. If `false`, returns only Tasks without addons. + :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 @@ -767,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( @@ -777,6 +1464,7 @@ async def list_async( 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, @@ -784,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, @@ -793,6 +1591,7 @@ def page( 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, @@ -810,8 +1609,9 @@ def page( :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 ordering: How to order the returned Task resources. y default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `Priority` or `DateCreated` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Multiple 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. - :param has_addons: Whether to read Tasks with addons. If `true`, returns only Tasks with addons. If `false`, returns only Tasks without addons. + :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 @@ -827,16 +1627,23 @@ def page( "TaskQueueSid": task_queue_sid, "TaskQueueName": task_queue_name, "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, "Ordering": ordering, - "HasAddons": has_addons, + "HasAddons": serialize.boolean_to_string(has_addons), "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TaskPage(self._version, response, self._solution) + 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 TaskPage(self._version, response, solution=self._solution) async def page_async( self, @@ -847,6 +1654,7 @@ async def page_async( 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, @@ -864,8 +1672,9 @@ async def page_async( :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 ordering: How to order the returned Task resources. y default, Tasks are sorted by ascending DateCreated. This value is specified as: `Attribute:Order`, where `Attribute` can be either `Priority` or `DateCreated` and `Order` can be either `asc` or `desc`. For example, `Priority:desc` returns Tasks ordered in descending order of their Priority. Multiple 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. - :param has_addons: Whether to read Tasks with addons. If `true`, returns only Tasks with addons. If `false`, returns only Tasks without addons. + :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 @@ -881,18 +1690,153 @@ async def page_async( "TaskQueueSid": task_queue_sid, "TaskQueueName": task_queue_name, "EvaluateTaskAttributes": evaluate_task_attributes, + "RoutingTarget": routing_target, "Ordering": ordering, - "HasAddons": has_addons, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return TaskPage(self._version, response, self._solution) + 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: """ @@ -904,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: """ @@ -916,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 32e7c6b4da..c6a845b47b 100644 --- a/twilio/rest/taskrouter/v1/workspace/task/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/task/reservation.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class ReservationInstance(InstanceResource): + class CallStatus(object): INITIATED = "initiated" RINGING = "ringing" @@ -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, @@ -200,6 +220,7 @@ def update( 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 @@ -249,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. @@ -258,6 +279,7 @@ def update( :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 """ @@ -316,6 +338,7 @@ def update( 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( @@ -380,6 +403,7 @@ async def update_async( 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 @@ -429,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. @@ -438,6 +462,7 @@ async def update_async( :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 """ @@ -496,85 +521,10 @@ async def update_async( 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 "".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 - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, @@ -636,9 +586,10 @@ def update( 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, - ) -> ReservationInstance: + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Update the ReservationInstance + Update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -685,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. @@ -694,91 +645,69 @@ def update( :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 + :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": call_accept, - "RedirectCallSid": redirect_call_sid, - "RedirectAccept": 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": record, - "Muted": muted, - "Beep": beep, - "StartConferenceOnEnter": start_conference_on_enter, - "EndConferenceOnExit": end_conference_on_exit, - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "EarlyMedia": 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": end_conference_on_customer_exit, - "BeepOnCustomerEntrance": beep_on_customer_entrance, - } - ) - headers = values.of( - { - "If-Match": if_match, - } - ) - - 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, @@ -840,9 +769,10 @@ async def update_async( 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, - ) -> ReservationInstance: + jitter_buffer_size: Union[str, object] = values.unset, + ) -> 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: @@ -889,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. @@ -898,60 +828,866 @@ async def update_async( :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 + :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": call_accept, - "RedirectCallSid": redirect_call_sid, - "RedirectAccept": 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": record, - "Muted": muted, - "Beep": beep, - "StartConferenceOnEnter": start_conference_on_enter, - "EndConferenceOnExit": end_conference_on_exit, - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "EarlyMedia": 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, + 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 "".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, + "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 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( @@ -960,27 +1696,410 @@ async def update_async( "PostWorkActivitySid": post_work_activity_sid, "SupervisorMode": supervisor_mode, "Supervisor": supervisor, - "EndConferenceOnCustomerExit": end_conference_on_customer_exit, - "BeepOnCustomerEntrance": beep_on_customer_entrance, + "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-Match": if_match, - } + 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"], ) - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers + 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: """ @@ -993,12 +2112,14 @@ def __repr__(self) -> str: class ReservationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: """ Build an instance of ReservationInstance :param payload: Payload response from the API """ + return ReservationInstance( self._version, payload, @@ -1016,6 +2137,7 @@ def __repr__(self) -> str: class ReservationList(ListResource): + def __init__(self, version: Version, workspace_sid: str, task_sid: str): """ Initialize the ReservationList @@ -1102,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, @@ -1125,6 +2311,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( reservation_status=reservation_status, @@ -1157,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( @@ -1167,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, @@ -1197,8 +2447,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ReservationPage(self._version, response, self._solution) + 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 ReservationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1230,10 +2486,96 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ReservationPage(self._version, response, self._solution) + 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 +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: """ @@ -1257,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 d6408dcd74..ea27998d19 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/task_channel.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class TaskChannelInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Task Channel resource. :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. @@ -68,6 +67,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[TaskChannelContext] = None @property @@ -104,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 @@ -122,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, @@ -158,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 @@ -169,6 +241,7 @@ def __repr__(self) -> str: class TaskChannelContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the TaskChannelContext @@ -188,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 @@ -195,9 +282,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -207,9 +316,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskChannelInstance 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) -> TaskChannelInstance: @@ -219,18 +352,45 @@ def fetch(self) -> TaskChannelInstance: :returns: The fetched TaskChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return TaskChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TaskChannelInstance: """ @@ -239,45 +399,77 @@ async def fetch_async(self) -> TaskChannelInstance: :returns: The fetched TaskChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TaskChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return TaskChannelInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, channel_optimized_routing: Union[bool, object] = values.unset, - ) -> TaskChannelInstance: + ) -> tuple: """ - Update the TaskChannelInstance + Internal helper for update operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, - "ChannelOptimizedRouting": channel_optimized_routing, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -285,32 +477,78 @@ 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( { "FriendlyName": friendly_name, - "ChannelOptimizedRouting": channel_optimized_routing, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -318,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 @@ -329,12 +592,14 @@ def __repr__(self) -> str: class TaskChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TaskChannelInstance: """ Build an instance of TaskChannelInstance :param payload: Payload response from the API """ + return TaskChannelInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -349,6 +614,7 @@ def __repr__(self) -> str: class TaskChannelList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the TaskChannelList @@ -365,6 +631,38 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/TaskChannels".format(**self._solution) + def _create( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "UniqueName": unique_name, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), + } + ) + 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, @@ -380,22 +678,70 @@ def create( :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"] + ) + + def create_with_http_info( + self, + friendly_name: str, + unique_name: str, + channel_optimized_routing: Union[bool, object] = values.unset, + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, "UniqueName": unique_name, - "ChannelOptimizedRouting": channel_optimized_routing, + "ChannelOptimizedRouting": serialize.boolean_to_string( + channel_optimized_routing + ), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return TaskChannelInstance( - self._version, payload, workspace_sid=self._solution["workspace_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( @@ -413,23 +759,39 @@ async def create_async( :returns: The created TaskChannelInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "UniqueName": unique_name, - "ChannelOptimizedRouting": channel_optimized_routing, - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + unique_name=unique_name, + channel_optimized_routing=channel_optimized_routing, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return TaskChannelInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - return TaskChannelInstance( + 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, @@ -481,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, @@ -500,6 +912,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -526,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( @@ -534,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, @@ -558,8 +1022,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TaskChannelPage(self._version, response, self._solution) + 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 TaskChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -585,10 +1055,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return TaskChannelPage(self._version, response, self._solution) + 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: """ @@ -600,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: """ @@ -612,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 cc523c8514..02213bbcc8 100644 --- a/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/__init__.py @@ -12,15 +12,18 @@ 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 +from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_bulk_real_time_statistics import ( + TaskQueueBulkRealTimeStatisticsList, +) from twilio.rest.taskrouter.v1.workspace.task_queue.task_queue_cumulative_statistics import ( TaskQueueCumulativeStatisticsList, ) @@ -36,6 +39,7 @@ class TaskQueueInstance(InstanceResource): + class TaskOrder(object): FIFO = "FIFO" LIFO = "LIFO" @@ -103,6 +107,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[TaskQueueContext] = None @property @@ -139,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 @@ -157,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, @@ -217,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: """ @@ -249,6 +350,7 @@ def __repr__(self) -> str: class TaskQueueContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the TaskQueueContext @@ -272,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 @@ -279,9 +395,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -291,9 +429,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TaskQueueInstance 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) -> TaskQueueInstance: @@ -303,18 +465,45 @@ def fetch(self) -> TaskQueueInstance: :returns: The fetched TaskQueueInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return TaskQueueInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TaskQueueInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TaskQueueInstance: """ @@ -323,20 +512,31 @@ async def fetch_async(self) -> TaskQueueInstance: :returns: The fetched TaskQueueInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TaskQueueInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return TaskQueueInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, target_workers: Union[str, object] = values.unset, @@ -344,19 +544,14 @@ 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( { "FriendlyName": friendly_name, @@ -367,13 +562,45 @@ def update( "TaskOrder": task_order, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -381,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, @@ -389,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. @@ -400,8 +627,40 @@ 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( { "FriendlyName": friendly_name, @@ -412,13 +671,45 @@ async def update_async( "TaskOrder": task_order, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -426,22 +717,59 @@ 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: - """ + :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: @@ -476,12 +804,14 @@ def __repr__(self) -> str: class TaskQueuePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TaskQueueInstance: """ Build an instance of TaskQueueInstance :param payload: Payload response from the API """ + return TaskQueueInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -496,6 +826,7 @@ def __repr__(self) -> str: class TaskQueueList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the TaskQueueList @@ -512,8 +843,47 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/TaskQueues".format(**self._solution) + self._bulk_real_time_statistics: Optional[ + TaskQueueBulkRealTimeStatisticsList + ] = None self._statistics: Optional[TaskQueuesStatisticsList] = None + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "TargetWorkers": target_workers, + "MaxReservedWorkers": max_reserved_workers, + "TaskOrder": task_order, + "ReservationActivitySid": reservation_activity_sid, + "AssignmentActivitySid": assignment_activity_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, friendly_name: str, @@ -535,6 +905,68 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "FriendlyName": friendly_name, @@ -545,15 +977,14 @@ def create( "AssignmentActivitySid": assignment_activity_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return TaskQueueInstance( - self._version, payload, workspace_sid=self._solution["workspace_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( @@ -577,26 +1008,51 @@ async def create_async( :returns: The created TaskQueueInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "TargetWorkers": target_workers, - "MaxReservedWorkers": max_reserved_workers, - "TaskOrder": task_order, - "ReservationActivitySid": reservation_activity_sid, - "AssignmentActivitySid": assignment_activity_sid, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return TaskQueueInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - return TaskQueueInstance( + 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, @@ -676,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, @@ -703,6 +1235,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -741,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( @@ -753,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, @@ -789,8 +1397,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TaskQueuePage(self._version, response, self._solution) + 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 TaskQueuePage(self._version, response, solution=self._solution) async def page_async( self, @@ -828,10 +1442,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return TaskQueuePage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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: """ @@ -843,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: """ @@ -855,7 +1567,18 @@ 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: + """ + Access the bulk_real_time_statistics + """ + if self._bulk_real_time_statistics is None: + self._bulk_real_time_statistics = TaskQueueBulkRealTimeStatisticsList( + self._version, workspace_sid=self._solution["workspace_sid"] + ) + return self._bulk_real_time_statistics @property def statistics(self) -> TaskQueuesStatisticsList: 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 new file mode 100644 index 0000000000..5273d75dea --- /dev/null +++ b/twilio/rest/taskrouter/v1/workspace/task_queue/task_queue_bulk_real_time_statistics.py @@ -0,0 +1,190 @@ +r""" + This code was generated by + ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __ + | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/ + | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \ + + Twilio - Taskrouter + 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 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 TaskQueueBulkRealTimeStatisticsInstance(InstanceResource): + """ + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. + :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. + :ivar task_queue_data: The real-time statistics for each requested TaskQueue SID. `task_queue_data` returns the following attributes: `task_queue_sid`: The SID of the TaskQueue from which these statistics were calculated. `total_available_workers`: The total number of Workers available for Tasks in the TaskQueue. `total_eligible_workers`: The total number of Workers eligible for Tasks in the TaskQueue, regardless of their Activity state. `total_tasks`: The total number of Tasks. `longest_task_waiting_age`: The age of the longest waiting Task. `longest_task_waiting_sid`: The SID of the longest waiting Task. `tasks_by_status`: The number of Tasks grouped by their current status. `tasks_by_priority`: The number of Tasks grouped by priority. `activity_statistics`: The number of current Workers grouped by Activity. + :ivar task_queue_response_count: The number of TaskQueue statistics received in task_queue_data. + :ivar url: The absolute URL of the TaskQueue statistics resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str): + super().__init__(version) + + self.account_sid: Optional[str] = payload.get("account_sid") + self.workspace_sid: Optional[str] = payload.get("workspace_sid") + self.task_queue_data: Optional[List[Dict[str, object]]] = payload.get( + "task_queue_data" + ) + self.task_queue_response_count: Optional[int] = deserialize.integer( + payload.get("task_queue_response_count") + ) + self.url: Optional[str] = payload.get("url") + + self._solution = { + "workspace_sid": workspace_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 TaskQueueBulkRealTimeStatisticsList(ListResource): + + def __init__(self, version: Version, workspace_sid: str): + """ + Initialize the TaskQueueBulkRealTimeStatisticsList + + :param version: Version that contains the resource + :param workspace_sid: The unique SID identifier of the Workspace. + + """ + super().__init__(version) + + # Path Solution + self._solution = { + "workspace_sid": workspace_sid, + } + self._uri = "/Workspaces/{workspace_sid}/TaskQueues/RealTimeStatistics".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 + ) -> 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"] + ) + + def create_with_http_info( + self, body: Union[object, object] = values.unset + ) -> ApiResponse: + """ + Create the TaskQueueBulkRealTimeStatisticsInstance and return response metadata + + :param body: + + :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() + + 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 + ) -> 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 + + :returns: Machine friendly representation + """ + return "" 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 94c213b626..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 @@ -12,10 +12,10 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,7 +23,6 @@ class TaskQueueCumulativeStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. @@ -96,9 +95,9 @@ def __init__( self.wait_duration_until_canceled: Optional[Dict[str, object]] = payload.get( "wait_duration_until_canceled" ) - self.wait_duration_in_queue_until_accepted: Optional[ - Dict[str, object] - ] = payload.get("wait_duration_in_queue_until_accepted") + self.wait_duration_in_queue_until_accepted: Optional[Dict[str, object]] = ( + payload.get("wait_duration_in_queue_until_accepted") + ) self.tasks_canceled: Optional[int] = deserialize.integer( payload.get("tasks_canceled") ) @@ -121,6 +120,7 @@ def __init__( "workspace_sid": workspace_sid, "task_queue_sid": task_queue_sid, } + self._context: Optional[TaskQueueCumulativeStatisticsContext] = None @property @@ -193,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 @@ -206,6 +260,7 @@ def __repr__(self) -> str: class TaskQueueCumulativeStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueCumulativeStatisticsContext @@ -225,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 + Internal helper for fetch operation - :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 + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -255,8 +305,40 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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, @@ -264,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. @@ -281,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) + + 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 - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -294,10 +405,40 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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, @@ -305,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 @@ -318,6 +493,7 @@ def __repr__(self) -> str: class TaskQueueCumulativeStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueCumulativeStatisticsList 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 d588f99d4d..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 @@ -12,9 +12,9 @@ Do not edit the class manually. """ - 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 @@ -22,7 +22,6 @@ class TaskQueueRealTimeStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. :ivar activity_statistics: The number of current Workers by Activity. @@ -33,7 +32,7 @@ class TaskQueueRealTimeStatisticsInstance(InstanceResource): :ivar task_queue_sid: The SID of the TaskQueue from which these statistics were calculated. :ivar tasks_by_priority: The number of Tasks by priority. For example: `{\"0\": \"10\", \"99\": \"5\"}` shows 10 Tasks at priority 0 and 5 at priority 99. :ivar tasks_by_status: The number of Tasks by their current status. For example: `{\"pending\": \"1\", \"reserved\": \"3\", \"assigned\": \"2\", \"completed\": \"5\"}`. - :ivar total_available_workers: The total number of Workers available for Tasks in the TaskQueue. + :ivar total_available_workers: The total number of Workers in the TaskQueue with an `available` status. Workers with an `available` status may already have active interactions or may have none. :ivar total_eligible_workers: The total number of Workers eligible for Tasks in the TaskQueue, independent of their Activity state. :ivar total_tasks: The total number of Tasks. :ivar workspace_sid: The SID of the Workspace that contains the TaskQueue. @@ -50,7 +49,7 @@ def __init__( super().__init__(version) self.account_sid: Optional[str] = payload.get("account_sid") - self.activity_statistics: Optional[List[object]] = payload.get( + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( "activity_statistics" ) self.longest_task_waiting_age: Optional[int] = deserialize.integer( @@ -88,6 +87,7 @@ def __init__( "workspace_sid": workspace_sid, "task_queue_sid": task_queue_sid, } + self._context: Optional[TaskQueueRealTimeStatisticsContext] = None @property @@ -134,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 @@ -147,6 +175,7 @@ def __repr__(self) -> str: class TaskQueueRealTimeStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueRealTimeStatisticsContext @@ -166,25 +195,39 @@ 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, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, 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, @@ -192,27 +235,60 @@ 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) - data = values.of( + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "TaskChannel": task_channel, } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, 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, @@ -220,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 @@ -233,6 +330,7 @@ def __repr__(self) -> str: class TaskQueueRealTimeStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueRealTimeStatisticsList 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 97fef95c2c..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 @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,7 +23,6 @@ class TaskQueueStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. :ivar cumulative: An object that contains the cumulative statistics for the TaskQueue. @@ -53,6 +52,7 @@ def __init__( "workspace_sid": workspace_sid, "task_queue_sid": task_queue_sid, } + self._context: Optional[TaskQueueStatisticsContext] = None @property @@ -125,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 @@ -136,6 +190,7 @@ def __repr__(self) -> str: class TaskQueueStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueStatisticsContext @@ -157,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 + Internal helper for fetch operation - :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 + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -187,8 +237,40 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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, @@ -196,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. @@ -213,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) + + 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 - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -226,10 +337,40 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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, @@ -237,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 @@ -248,6 +423,7 @@ def __repr__(self) -> str: class TaskQueueStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str, task_queue_sid: str): """ Initialize the TaskQueueStatisticsList 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 091715e7dd..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 @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,7 +24,6 @@ class TaskQueuesStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the TaskQueue resource. :ivar cumulative: An object that contains the cumulative statistics for the TaskQueues. @@ -57,12 +56,14 @@ def __repr__(self) -> str: class TaskQueuesStatisticsPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TaskQueuesStatisticsInstance: """ Build an instance of TaskQueuesStatisticsInstance :param payload: Payload response from the API """ + return TaskQueuesStatisticsInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -77,6 +78,7 @@ def __repr__(self) -> str: class TaskQueuesStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the TaskQueuesStatisticsList @@ -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, @@ -316,8 +494,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TaskQueuesStatisticsPage(self._version, response, self._solution) + 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 TaskQueuesStatisticsPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -361,10 +547,126 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 ) - return TaskQueuesStatisticsPage(self._version, response, self._solution) + 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: """ @@ -376,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: """ @@ -388,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 0e12630f2c..1295d3716e 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/__init__.py @@ -12,10 +12,10 @@ 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 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 @@ -38,7 +38,6 @@ class WorkerInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. :ivar activity_name: The `friendly_name` of the Worker's current Activity. @@ -88,6 +87,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[WorkerContext] = None @property @@ -130,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 @@ -148,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, @@ -202,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: """ @@ -234,6 +334,7 @@ def __repr__(self) -> str: class WorkerContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the WorkerContext @@ -255,6 +356,25 @@ 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) -> tuple: + """ + Internal helper for delete operation + + Returns: + tuple: (success_boolean, status_code, headers) + """ + headers = values.of( + { + "If-Match": if_match, + } + ) + + headers = values.of({}) + + return self._version.delete_with_response_info( + method="DELETE", uri=self._uri, headers=headers + ) + def delete(self, if_match: Union[str, object] = values.unset) -> bool: """ Deletes the WorkerInstance @@ -263,13 +383,40 @@ def delete(self, if_match: Union[str, object] = values.unset) -> bool: :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, } ) - return self._version.delete(method="DELETE", uri=self._uri, headers=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, if_match: Union[str, object] = values.unset) -> bool: """ @@ -279,14 +426,36 @@ async def delete_async(self, if_match: Union[str, object] = values.unset) -> boo :returns: True if delete succeeds, False otherwise """ - headers = values.of( - { - "If-Match": if_match, - } - ) + success, _, _ = await self._delete_async(if_match=if_match) + return success - return await self._version.delete_async( - method="DELETE", uri=self._uri, headers=headers + 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" + + return self._version.fetch_with_response_info( + method="GET", uri=self._uri, headers=headers ) def fetch(self) -> WorkerInstance: @@ -296,18 +465,45 @@ def fetch(self) -> WorkerInstance: :returns: The fetched WorkerInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return WorkerInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkerInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WorkerInstance: """ @@ -316,56 +512,96 @@ async def fetch_async(self) -> WorkerInstance: :returns: The fetched WorkerInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WorkerInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return WorkerInstance( + 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( + 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( { "ActivitySid": activity_sid, "Attributes": attributes, "FriendlyName": friendly_name, - "RejectPendingReservations": reject_pending_reservations, - } - ) - headers = values.of( - { - "If-Match": if_match, + "RejectPendingReservations": serialize.boolean_to_string( + reject_pending_reservations + ), } ) + headers = values.of({}) - payload = self._version.update( + 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, + 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, @@ -373,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. @@ -390,26 +626,89 @@ 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( { "ActivitySid": activity_sid, "Attributes": attributes, "FriendlyName": friendly_name, - "RejectPendingReservations": reject_pending_reservations, - } - ) - headers = values.of( - { - "If-Match": if_match, + "RejectPendingReservations": serialize.boolean_to_string( + reject_pending_reservations + ), } ) + headers = values.of({}) + + if not ( + if_match is values.unset or (isinstance(if_match, str) and not if_match) + ): + headers["If-Match"] = if_match - payload = await self._version.update_async( + 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, + 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, @@ -417,11 +716,45 @@ 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: + """ + Asynchronous coroutine to 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. + :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, @@ -467,12 +800,14 @@ def __repr__(self) -> str: class WorkerPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> WorkerInstance: """ Build an instance of WorkerInstance :param payload: Payload response from the API """ + return WorkerInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -487,6 +822,7 @@ def __repr__(self) -> str: class WorkerList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkerList @@ -507,6 +843,36 @@ def __init__(self, version: Version, workspace_sid: str): self._real_time_statistics: Optional[WorkersRealTimeStatisticsList] = None self._statistics: Optional[WorkersStatisticsList] = None + def _create( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "ActivitySid": activity_sid, + "Attributes": attributes, + } + ) + 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, @@ -522,6 +888,53 @@ def create( :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"] + ) + + def create_with_http_info( + self, + friendly_name: str, + activity_sid: Union[str, object] = values.unset, + attributes: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, @@ -529,15 +942,14 @@ def create( "Attributes": attributes, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WorkerInstance( - self._version, payload, workspace_sid=self._solution["workspace_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( @@ -555,23 +967,39 @@ async def create_async( :returns: The created WorkerInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "ActivitySid": activity_sid, - "Attributes": attributes, - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + activity_sid=activity_sid, + attributes=attributes, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return WorkerInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - return WorkerInstance( + 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, @@ -596,7 +1024,7 @@ def stream( :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 on a TaskQueue. This is helpful for debugging which Workers would match a potential queue. + :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 @@ -647,7 +1075,7 @@ async def stream_async( :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 on a TaskQueue. This is helpful for debugging which Workers would match a potential queue. + :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 @@ -675,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, @@ -697,7 +1225,7 @@ def list( :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 on a TaskQueue. This is helpful for debugging which Workers would match a potential queue. + :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 @@ -710,6 +1238,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( activity_name=activity_name, @@ -747,7 +1276,7 @@ async def list_async( :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 on a TaskQueue. This is helpful for debugging which Workers would match a potential queue. + :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 @@ -760,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( @@ -776,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, @@ -798,7 +1426,7 @@ def page( :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 on a TaskQueue. This is helpful for debugging which Workers would match a potential queue. + :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 @@ -824,8 +1452,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return WorkerPage(self._version, response, self._solution) + 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 WorkerPage(self._version, response, solution=self._solution) async def page_async( self, @@ -849,7 +1483,7 @@ async def page_async( :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 on a TaskQueue. This is helpful for debugging which Workers would match a potential queue. + :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 @@ -875,10 +1509,132 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return WorkerPage(self._version, response, self._solution) + 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: """ @@ -890,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: """ @@ -902,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 e99705d669..227b2b83d7 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/reservation.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/reservation.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class ReservationInstance(InstanceResource): + class CallStatus(object): INITIATED = "initiated" RINGING = "ringing" @@ -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, @@ -191,6 +211,7 @@ def update( 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 @@ -240,13 +261,14 @@ 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. :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 """ @@ -303,6 +325,7 @@ def update( 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( @@ -363,6 +386,7 @@ async def update_async( 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 @@ -412,13 +436,14 @@ 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. :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 """ @@ -475,83 +500,10 @@ async def update_async( 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 "".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 - """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, - ) - - 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 - """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - - 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, @@ -609,9 +561,10 @@ def update( 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, - ) -> ReservationInstance: + jitter_buffer_size: Union[str, object] = values.unset, + ) -> ApiResponse: """ - Update the ReservationInstance + Update the ReservationInstance with HTTP info :param if_match: The If-Match HTTP request header :param reservation_status: @@ -658,96 +611,74 @@ 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. :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 + :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": call_accept, - "RedirectCallSid": redirect_call_sid, - "RedirectAccept": 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": record, - "Muted": muted, - "Beep": beep, - "StartConferenceOnEnter": start_conference_on_enter, - "EndConferenceOnExit": end_conference_on_exit, - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "EarlyMedia": 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": end_conference_on_customer_exit, - "BeepOnCustomerEntrance": beep_on_customer_entrance, - } - ) - headers = values.of( - { - "If-Match": if_match, - } - ) - - 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, @@ -805,9 +736,10 @@ async def update_async( 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, - ) -> ReservationInstance: + jitter_buffer_size: Union[str, object] = values.unset, + ) -> 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: @@ -854,94 +786,1237 @@ 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. :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 + :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": call_accept, - "RedirectCallSid": redirect_call_sid, - "RedirectAccept": 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": record, - "Muted": muted, - "Beep": beep, - "StartConferenceOnEnter": start_conference_on_enter, - "EndConferenceOnExit": end_conference_on_exit, - "WaitUrl": wait_url, - "WaitMethod": wait_method, - "EarlyMedia": 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": end_conference_on_customer_exit, - "BeepOnCustomerEntrance": beep_on_customer_entrance, + 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 "".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), + "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-Match": if_match, - } + 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, + 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"], ) - payload = await self._version.update_async( - method="POST", uri=self._uri, data=data, headers=headers - ) + 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`. - return ReservationInstance( + :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, + ) + 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: """ @@ -954,12 +2029,14 @@ def __repr__(self) -> str: class ReservationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ReservationInstance: """ Build an instance of ReservationInstance :param payload: Payload response from the API """ + return ReservationInstance( self._version, payload, @@ -977,6 +2054,7 @@ def __repr__(self) -> str: class ReservationList(ListResource): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ Initialize the ReservationList @@ -1057,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, @@ -1078,6 +2212,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( reservation_status=reservation_status, @@ -1107,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( @@ -1116,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, @@ -1143,8 +2335,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ReservationPage(self._version, response, self._solution) + 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 ReservationPage(self._version, response, solution=self._solution) async def page_async( self, @@ -1173,10 +2371,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ReservationPage(self._version, response, self._solution) + 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: """ @@ -1188,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: """ @@ -1200,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 74c8531af6..61d407fd38 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_channel.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class WorkerChannelInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. :ivar assigned_tasks: The total number of Tasks assigned to Worker for the TaskChannel type. @@ -82,6 +81,7 @@ def __init__( "worker_sid": worker_sid, "sid": sid or self.sid, } + self._context: Optional[WorkerChannelContext] = None @property @@ -119,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, @@ -155,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 @@ -166,6 +220,7 @@ def __repr__(self) -> str: class WorkerChannelContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: str): """ Initialize the WorkerChannelContext @@ -189,6 +244,22 @@ def __init__(self, version: Version, workspace_sid: str, worker_sid: str, sid: s ) ) + 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) -> WorkerChannelInstance: """ Fetch the WorkerChannelInstance @@ -196,19 +267,47 @@ def fetch(self) -> WorkerChannelInstance: :returns: The fetched WorkerChannelInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], ) - return WorkerChannelInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkerChannelInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WorkerChannelInstance: """ @@ -217,46 +316,74 @@ async def fetch_async(self) -> WorkerChannelInstance: :returns: The fetched WorkerChannelInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WorkerChannelInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + worker_sid=self._solution["worker_sid"], + sid=self._solution["sid"], ) - return WorkerChannelInstance( + 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( + def _update( self, capacity: Union[int, object] = values.unset, available: Union[bool, object] = values.unset, - ) -> WorkerChannelInstance: + ) -> tuple: """ - Update the WorkerChannelInstance + Internal helper for update operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "Capacity": capacity, - "Available": available, + "Available": serialize.boolean_to_string(available), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -265,32 +392,73 @@ 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( { "Capacity": capacity, - "Available": available, + "Available": serialize.boolean_to_string(available), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -299,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 @@ -310,12 +503,14 @@ def __repr__(self) -> str: class WorkerChannelPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> WorkerChannelInstance: """ Build an instance of WorkerChannelInstance :param payload: Payload response from the API """ + return WorkerChannelInstance( self._version, payload, @@ -333,6 +528,7 @@ def __repr__(self) -> str: class WorkerChannelList(ListResource): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ Initialize the WorkerChannelList @@ -403,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, @@ -422,6 +668,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -448,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( @@ -456,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, @@ -480,8 +778,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return WorkerChannelPage(self._version, response, self._solution) + 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 WorkerChannelPage(self._version, response, solution=self._solution) async def page_async( self, @@ -507,10 +811,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return WorkerChannelPage(self._version, response, self._solution) + 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: """ @@ -522,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: """ @@ -534,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 7724d5caf0..f2fbcd5c34 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/worker_statistics.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,7 +23,6 @@ class WorkerStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. :ivar cumulative: An object that contains the cumulative statistics for the Worker. @@ -51,6 +50,7 @@ def __init__( "workspace_sid": workspace_sid, "worker_sid": worker_sid, } + self._context: Optional[WorkerStatisticsContext] = None @property @@ -117,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 @@ -128,6 +176,7 @@ def __repr__(self) -> str: class WorkerStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ Initialize the WorkerStatisticsContext @@ -149,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 + 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 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: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -176,8 +221,37 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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, @@ -185,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), @@ -212,10 +313,37 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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, @@ -223,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 @@ -234,6 +393,7 @@ def __repr__(self) -> str: class WorkerStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str, worker_sid: str): """ Initialize the WorkerStatisticsList 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 14310b05bb..dbcce53c8c 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_cumulative_statistics.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,7 +23,6 @@ class WorkersCumulativeStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. :ivar start_time: The beginning of the interval during which these statistics were calculated, in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. @@ -49,7 +48,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str self.end_time: Optional[datetime] = deserialize.iso8601_datetime( payload.get("end_time") ) - self.activity_durations: Optional[List[object]] = payload.get( + self.activity_durations: Optional[List[Dict[str, object]]] = payload.get( "activity_durations" ) self.reservations_created: Optional[int] = deserialize.integer( @@ -76,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 @@ -141,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 @@ -154,6 +202,7 @@ def __repr__(self) -> str: class WorkersCumulativeStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkersCumulativeStatisticsContext @@ -171,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 - - :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`. + Internal helper for fetch operation - :returns: The fetched WorkersCumulativeStatisticsInstance + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -198,33 +243,88 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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) - 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, + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -233,16 +333,73 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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 @@ -256,6 +413,7 @@ def __repr__(self) -> str: class WorkersCumulativeStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkersCumulativeStatisticsList 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 c59611dcfa..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 @@ -12,9 +12,9 @@ Do not edit the class manually. """ - 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 @@ -22,7 +22,6 @@ class WorkersRealTimeStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Worker resource. :ivar activity_statistics: The number of current Workers by Activity. @@ -35,7 +34,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str super().__init__(version) self.account_sid: Optional[str] = payload.get("account_sid") - self.activity_statistics: Optional[List[object]] = payload.get( + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( "activity_statistics" ) self.total_workers: Optional[int] = deserialize.integer( @@ -47,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 @@ -92,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 @@ -105,6 +133,7 @@ def __repr__(self) -> str: class WorkersRealTimeStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkersRealTimeStatisticsContext @@ -122,6 +151,28 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) + def _fetch(self, task_channel: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "TaskChannel": task_channel, + } + ) + + 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, task_channel: Union[str, object] = values.unset ) -> WorkersRealTimeStatisticsInstance: @@ -132,19 +183,53 @@ def fetch( :returns: The fetched WorkersRealTimeStatisticsInstance """ + payload, _, _ = self._fetch(task_channel=task_channel) + return WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + headers = values.of({}) - return WorkersRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], + 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( @@ -157,22 +242,32 @@ async def fetch_async( :returns: The fetched WorkersRealTimeStatisticsInstance """ - - data = values.of( - { - "TaskChannel": task_channel, - } + payload, _, _ = await self._fetch_async(task_channel=task_channel) + return WorkersRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return 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: 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: """ @@ -187,6 +282,7 @@ def __repr__(self) -> str: class WorkersRealTimeStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkersRealTimeStatisticsList diff --git a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py index 58ef59969b..8a3a21b6bb 100644 --- a/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/worker/workers_statistics.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,7 +23,6 @@ class WorkersStatisticsInstance(InstanceResource): - """ :ivar realtime: An object that contains the real-time statistics for the Worker. :ivar cumulative: An object that contains the cumulative statistics for the Worker. @@ -44,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 @@ -127,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 @@ -138,6 +204,7 @@ def __repr__(self) -> str: class WorkersStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkersStatisticsContext @@ -155,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, @@ -164,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), @@ -191,15 +251,53 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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, @@ -208,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. @@ -220,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), @@ -235,16 +365,91 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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 @@ -256,6 +461,7 @@ def __repr__(self) -> str: class WorkersStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkersStatisticsList diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py index 04cbba20b7..547db90579 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/__init__.py @@ -12,10 +12,10 @@ 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 @@ -33,7 +33,6 @@ class WorkflowInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. :ivar assignment_callback_url: The URL that we call when a task managed by the Workflow is assigned to a Worker. See Assignment Callback URL for more information. @@ -87,6 +86,7 @@ def __init__( "workspace_sid": workspace_sid, "sid": sid or self.sid, } + self._context: Optional[WorkflowContext] = None @property @@ -123,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 @@ -141,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, @@ -201,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: """ @@ -233,6 +329,7 @@ def __repr__(self) -> str: class WorkflowContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, sid: str): """ Initialize the WorkflowContext @@ -256,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 @@ -263,9 +374,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -275,9 +408,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WorkflowInstance 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) -> WorkflowInstance: @@ -287,18 +444,45 @@ def fetch(self) -> WorkflowInstance: :returns: The fetched WorkflowInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return WorkflowInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WorkflowInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WorkflowInstance: """ @@ -307,20 +491,31 @@ async def fetch_async(self) -> WorkflowInstance: :returns: The fetched WorkflowInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WorkflowInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + sid=self._solution["sid"], ) - return WorkflowInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, assignment_callback_url: Union[str, object] = values.unset, @@ -328,19 +523,14 @@ 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( { "FriendlyName": friendly_name, @@ -351,13 +541,45 @@ def update( "ReEvaluateTasks": re_evaluate_tasks, } ) + 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, + 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, @@ -365,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, @@ -373,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. @@ -384,8 +606,40 @@ 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( { "FriendlyName": friendly_name, @@ -396,13 +650,45 @@ async def update_async( "ReEvaluateTasks": re_evaluate_tasks, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -410,23 +696,60 @@ async def update_async( sid=self._solution["sid"], ) - @property - def cumulative_statistics(self) -> WorkflowCumulativeStatisticsList: - """ - Access the cumulative_statistics + 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: """ - if self._cumulative_statistics is None: - self._cumulative_statistics = WorkflowCumulativeStatisticsList( - self._version, - self._solution["workspace_sid"], - self._solution["sid"], - ) - return self._cumulative_statistics + Asynchronous coroutine to update the WorkflowInstance and return response metadata - @property - def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: - """ - Access the real_time_statistics + :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: + """ + Access the cumulative_statistics + """ + if self._cumulative_statistics is None: + self._cumulative_statistics = WorkflowCumulativeStatisticsList( + self._version, + self._solution["workspace_sid"], + self._solution["sid"], + ) + return self._cumulative_statistics + + @property + def real_time_statistics(self) -> WorkflowRealTimeStatisticsList: + """ + Access the real_time_statistics """ if self._real_time_statistics is None: self._real_time_statistics = WorkflowRealTimeStatisticsList( @@ -460,12 +783,14 @@ def __repr__(self) -> str: class WorkflowPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> WorkflowInstance: """ Build an instance of WorkflowInstance :param payload: Payload response from the API """ + return WorkflowInstance( self._version, payload, workspace_sid=self._solution["workspace_sid"] ) @@ -480,6 +805,7 @@ def __repr__(self) -> str: class WorkflowList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkflowList @@ -496,6 +822,40 @@ def __init__(self, version: Version, workspace_sid: str): } self._uri = "/Workspaces/{workspace_sid}/Workflows".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Configuration": configuration, + "AssignmentCallbackUrl": assignment_callback_url, + "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, + "TaskReservationTimeout": task_reservation_timeout, + } + ) + 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, @@ -515,6 +875,63 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, @@ -524,15 +941,14 @@ def create( "TaskReservationTimeout": task_reservation_timeout, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WorkflowInstance( - self._version, payload, workspace_sid=self._solution["workspace_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( @@ -554,25 +970,47 @@ async def create_async( :returns: The created WorkflowInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Configuration": configuration, - "AssignmentCallbackUrl": assignment_callback_url, - "FallbackAssignmentCallbackUrl": fallback_assignment_callback_url, - "TaskReservationTimeout": task_reservation_timeout, - } + 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, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return WorkflowInstance( + self._version, payload, workspace_sid=self._solution["workspace_sid"] ) - return WorkflowInstance( + 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, @@ -630,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, @@ -651,6 +1145,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -680,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( @@ -689,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, @@ -716,8 +1268,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return WorkflowPage(self._version, response, self._solution) + 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 WorkflowPage(self._version, response, solution=self._solution) async def page_async( self, @@ -746,10 +1304,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return WorkflowPage(self._version, response, self._solution) + 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: """ @@ -761,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: """ @@ -773,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 28e557b8c2..f104fd41bb 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_cumulative_statistics.py @@ -12,10 +12,10 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,7 +23,6 @@ class WorkflowCumulativeStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. @@ -121,6 +120,7 @@ def __init__( "workspace_sid": workspace_sid, "workflow_sid": workflow_sid, } + self._context: Optional[WorkflowCumulativeStatisticsContext] = None @property @@ -193,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 @@ -206,6 +260,7 @@ def __repr__(self) -> str: class WorkflowCumulativeStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowCumulativeStatisticsContext @@ -225,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 + Internal helper for fetch operation - :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 + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -255,8 +305,40 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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, @@ -264,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. @@ -281,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) + + 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 - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -294,10 +405,40 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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, @@ -305,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 @@ -318,6 +493,7 @@ def __repr__(self) -> str: class WorkflowCumulativeStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowCumulativeStatisticsList 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 55a41f5d84..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 @@ -12,9 +12,9 @@ Do not edit the class manually. """ - 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 @@ -22,7 +22,6 @@ class WorkflowRealTimeStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. :ivar longest_task_waiting_age: The age of the longest waiting Task. @@ -68,6 +67,7 @@ def __init__( "workspace_sid": workspace_sid, "workflow_sid": workflow_sid, } + self._context: Optional[WorkflowRealTimeStatisticsContext] = None @property @@ -114,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 @@ -127,6 +155,7 @@ def __repr__(self) -> str: class WorkflowRealTimeStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowRealTimeStatisticsContext @@ -146,25 +175,39 @@ 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, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, 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, @@ -172,27 +215,60 @@ 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) - data = values.of( + async def _fetch_async( + self, task_channel: Union[str, object] = values.unset + ) -> tuple: + """ + Internal async helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "TaskChannel": task_channel, } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, 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, @@ -200,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 @@ -213,6 +310,7 @@ def __repr__(self) -> str: class WorkflowRealTimeStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowRealTimeStatisticsList diff --git a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py index 521b2921b7..1aa812c61d 100644 --- a/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workflow/workflow_statistics.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,7 +23,6 @@ class WorkflowStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workflow resource. :ivar cumulative: An object that contains the cumulative statistics for the Workflow. @@ -53,6 +52,7 @@ def __init__( "workspace_sid": workspace_sid, "workflow_sid": workflow_sid, } + self._context: Optional[WorkflowStatisticsContext] = None @property @@ -125,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 @@ -136,6 +190,7 @@ def __repr__(self) -> str: class WorkflowStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowStatisticsContext @@ -157,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 + 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_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: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -187,8 +237,40 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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, @@ -196,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. @@ -213,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) + + 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 - data = values.of( + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -226,10 +337,40 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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, @@ -237,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 @@ -248,6 +423,7 @@ def __repr__(self) -> str: class WorkflowStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str, workflow_sid: str): """ Initialize the WorkflowStatisticsList diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py index 71e8a56a7a..8d7262cdb0 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_cumulative_statistics.py @@ -12,10 +12,10 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,7 +23,6 @@ class WorkspaceCumulativeStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. :ivar avg_task_acceptance_time: The average time in seconds between Task creation and acceptance. @@ -112,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 @@ -183,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 @@ -196,6 +250,7 @@ def __repr__(self) -> str: class WorkspaceCumulativeStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkspaceCumulativeStatisticsContext @@ -213,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 + Internal helper for fetch operation - :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 + Returns: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "EndDate": serialize.iso8601_datetime(end_date), "Minutes": minutes, @@ -243,24 +293,56 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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. @@ -268,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, @@ -281,16 +391,79 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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 @@ -304,6 +477,7 @@ def __repr__(self) -> str: class WorkspaceCumulativeStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkspaceCumulativeStatisticsList 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 d69600d7f2..559ec20f14 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_real_time_statistics.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - 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 @@ -22,7 +22,6 @@ class WorkspaceRealTimeStatisticsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Workspace resource. :ivar activity_statistics: The number of current Workers by Activity. @@ -40,7 +39,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], workspace_sid: str super().__init__(version) self.account_sid: Optional[str] = payload.get("account_sid") - self.activity_statistics: Optional[List[object]] = payload.get( + self.activity_statistics: Optional[List[Dict[str, object]]] = payload.get( "activity_statistics" ) self.longest_task_waiting_age: Optional[int] = deserialize.integer( @@ -67,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 @@ -112,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 @@ -125,6 +153,7 @@ def __repr__(self) -> str: class WorkspaceRealTimeStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkspaceRealTimeStatisticsContext @@ -142,6 +171,28 @@ def __init__(self, version: Version, workspace_sid: str): **self._solution ) + def _fetch(self, task_channel: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for fetch operation + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( + { + "TaskChannel": task_channel, + } + ) + + 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, task_channel: Union[str, object] = values.unset ) -> WorkspaceRealTimeStatisticsInstance: @@ -152,19 +203,53 @@ def fetch( :returns: The fetched WorkspaceRealTimeStatisticsInstance """ + payload, _, _ = self._fetch(task_channel=task_channel) + return WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], + ) + + def fetch_with_http_info( + self, task_channel: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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, } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + headers = values.of({}) - return WorkspaceRealTimeStatisticsInstance( - self._version, - payload, - workspace_sid=self._solution["workspace_sid"], + 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( @@ -177,22 +262,32 @@ async def fetch_async( :returns: The fetched WorkspaceRealTimeStatisticsInstance """ - - data = values.of( - { - "TaskChannel": task_channel, - } + payload, _, _ = await self._fetch_async(task_channel=task_channel) + return WorkspaceRealTimeStatisticsInstance( + self._version, + payload, + workspace_sid=self._solution["workspace_sid"], ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data - ) + 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 - return 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: 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: """ @@ -207,6 +302,7 @@ def __repr__(self) -> str: class WorkspaceRealTimeStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkspaceRealTimeStatisticsList diff --git a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py index 443ee93903..e30fecf3e1 100644 --- a/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py +++ b/twilio/rest/taskrouter/v1/workspace/workspace_statistics.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,7 +23,6 @@ class WorkspaceStatisticsInstance(InstanceResource): - """ :ivar realtime: An object that contains the real-time statistics for the Workspace. :ivar cumulative: An object that contains the cumulative statistics for the Workspace. @@ -44,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 @@ -115,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 @@ -126,6 +180,7 @@ def __repr__(self) -> str: class WorkspaceStatisticsContext(InstanceContext): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkspaceStatisticsContext @@ -141,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 + 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_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: + tuple: (payload, status_code, headers) """ - data = values.of( + params = values.of( { "Minutes": minutes, "StartDate": serialize.iso8601_datetime(start_date), @@ -171,24 +221,56 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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. @@ -196,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), @@ -209,16 +319,79 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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 @@ -230,6 +403,7 @@ def __repr__(self) -> str: class WorkspaceStatisticsList(ListResource): + def __init__(self, version: Version, workspace_sid: str): """ Initialize the WorkspaceStatisticsList diff --git a/twilio/rest/trunking/TrunkingBase.py b/twilio/rest/trunking/TrunkingBase.py index 627790454d..bed8f9a2a9 100644 --- a/twilio/rest/trunking/TrunkingBase.py +++ b/twilio/rest/trunking/TrunkingBase.py @@ -17,6 +17,7 @@ class TrunkingBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Trunking Domain diff --git a/twilio/rest/trunking/v1/__init__.py b/twilio/rest/trunking/v1/__init__.py index 89dc5c1087..af530b97c7 100644 --- a/twilio/rest/trunking/v1/__init__.py +++ b/twilio/rest/trunking/v1/__init__.py @@ -19,6 +19,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Trunking diff --git a/twilio/rest/trunking/v1/trunk/__init__.py b/twilio/rest/trunking/v1/trunk/__init__.py index e7a0aa5cfd..7697c323b6 100644 --- a/twilio/rest/trunking/v1/trunk/__init__.py +++ b/twilio/rest/trunking/v1/trunk/__init__.py @@ -12,10 +12,10 @@ 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 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 +29,7 @@ class TrunkInstance(InstanceResource): + class TransferCallerId(object): FROM_TRANSFEREE = "from-transferee" FROM_TRANSFEROR = "from-transferor" @@ -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. @@ -75,11 +77,14 @@ def __init__( self.transfer_mode: Optional["TrunkInstance.TransferSetting"] = payload.get( "transfer_mode" ) - self.transfer_caller_id: Optional[ - "TrunkInstance.TransferCallerId" - ] = payload.get("transfer_caller_id") + self.transfer_caller_id: Optional["TrunkInstance.TransferCallerId"] = ( + payload.get("transfer_caller_id") + ) 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: """ @@ -269,6 +387,7 @@ def __repr__(self) -> str: class TrunkContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the TrunkContext @@ -290,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 @@ -297,9 +430,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -309,9 +464,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrunkInstance 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) -> TrunkInstance: @@ -321,17 +500,43 @@ def fetch(self) -> TrunkInstance: :returns: The fetched TrunkInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return TrunkInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrunkInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TrunkInstance: """ @@ -340,17 +545,69 @@ async def fetch_async(self) -> TrunkInstance: :returns: The fetched TrunkInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TrunkInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return TrunkInstance( + 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, + 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 helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_id, + } + ) + 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, @@ -379,28 +636,19 @@ def update( :returns: The updated TrunkInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "DomainName": domain_name, - "DisasterRecoveryUrl": disaster_recovery_url, - "DisasterRecoveryMethod": disaster_recovery_method, - "TransferMode": transfer_mode, - "Secure": secure, - "CnamLookupEnabled": cnam_lookup_enabled, - "TransferCallerId": transfer_caller_id, - } - ) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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"]) - async def update_async( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, domain_name: Union[str, object] = values.unset, @@ -412,9 +660,9 @@ async def update_async( transfer_caller_id: Union[ "TrunkInstance.TransferCallerId", object ] = values.unset, - ) -> TrunkInstance: + ) -> ApiResponse: """ - Asynchronous coroutine to update the TrunkInstance + 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. @@ -425,8 +673,41 @@ async def update_async( :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 + :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( { "FriendlyName": friendly_name, @@ -434,45 +715,125 @@ async def update_async( "DisasterRecoveryUrl": disaster_recovery_url, "DisasterRecoveryMethod": disaster_recovery_method, "TransferMode": transfer_mode, - "Secure": secure, - "CnamLookupEnabled": cnam_lookup_enabled, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), "TransferCallerId": transfer_caller_id, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return TrunkInstance(self._version, payload, sid=self._solution["sid"]) + headers["Content-Type"] = "application/x-www-form-urlencoded" - @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 + headers["Accept"] = "application/json" - @property - def ip_access_control_lists(self) -> IpAccessControlListList: - """ - Access the ip_access_control_lists - """ - if self._ip_access_control_lists is None: - self._ip_access_control_lists = IpAccessControlListList( - self._version, - self._solution["sid"], - ) - return self._ip_access_control_lists + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - @property + 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: + """ + Asynchronous coroutine to 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: + + :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 + """ + if self._ip_access_control_lists is None: + self._ip_access_control_lists = IpAccessControlListList( + self._version, + self._solution["sid"], + ) + return self._ip_access_control_lists + + @property def origination_urls(self) -> OriginationUrlList: """ Access the origination_urls @@ -519,12 +880,14 @@ def __repr__(self) -> str: class TrunkPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TrunkInstance: """ Build an instance of TrunkInstance :param payload: Payload response from the API """ + return TrunkInstance(self._version, payload) def __repr__(self) -> str: @@ -537,6 +900,7 @@ def __repr__(self) -> str: class TrunkList(ListResource): + def __init__(self, version: Version): """ Initialize the TrunkList @@ -548,6 +912,48 @@ def __init__(self, version: Version): self._uri = "/Trunks" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "DomainName": domain_name, + "DisasterRecoveryUrl": disaster_recovery_url, + "DisasterRecoveryMethod": disaster_recovery_method, + "TransferMode": transfer_mode, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "TransferCallerId": transfer_caller_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, friendly_name: Union[str, object] = values.unset, @@ -575,6 +981,78 @@ def create( :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( { "FriendlyName": friendly_name, @@ -582,19 +1060,20 @@ def create( "DisasterRecoveryUrl": disaster_recovery_url, "DisasterRecoveryMethod": disaster_recovery_method, "TransferMode": transfer_mode, - "Secure": secure, - "CnamLookupEnabled": cnam_lookup_enabled, + "Secure": serialize.boolean_to_string(secure), + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), "TransferCallerId": transfer_caller_id, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return TrunkInstance(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, @@ -623,26 +1102,57 @@ async def create_async( :returns: The created TrunkInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "DomainName": domain_name, - "DisasterRecoveryUrl": disaster_recovery_url, - "DisasterRecoveryMethod": disaster_recovery_method, - "TransferMode": transfer_mode, - "Secure": secure, - "CnamLookupEnabled": cnam_lookup_enabled, - "TransferCallerId": transfer_caller_id, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return TrunkInstance(self._version, payload) + :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, @@ -694,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, @@ -713,6 +1273,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -739,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( @@ -747,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, @@ -771,7 +1383,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 TrunkPage(self._version, response) async def page_async( @@ -798,11 +1416,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 805d66260d..540c501396 100644 --- a/twilio/rest/trunking/v1/trunk/credential_list.py +++ b/twilio/rest/trunking/v1/trunk/credential_list.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class CredentialListInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CredentialList resource. :ivar sid: The unique string that we created to identify the CredentialList resource. @@ -60,6 +59,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[CredentialListContext] = None @property @@ -96,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 @@ -114,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 @@ -125,6 +161,7 @@ def __repr__(self) -> str: class CredentialListContext(InstanceContext): + def __init__(self, version: Version, trunk_sid: str, sid: str): """ Initialize the CredentialListContext @@ -142,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 @@ -149,9 +200,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -161,9 +234,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CredentialListInstance 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) -> CredentialListInstance: @@ -173,18 +270,45 @@ def fetch(self) -> CredentialListInstance: :returns: The fetched CredentialListInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], ) - return CredentialListInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CredentialListInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CredentialListInstance: """ @@ -193,18 +317,29 @@ async def fetch_async(self) -> CredentialListInstance: :returns: The fetched CredentialListInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CredentialListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], ) - return CredentialListInstance( + 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: """ @@ -217,12 +352,14 @@ def __repr__(self) -> str: class CredentialListPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CredentialListInstance: """ Build an instance of CredentialListInstance :param payload: Payload response from the API """ + return CredentialListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -237,6 +374,7 @@ def __repr__(self) -> str: class CredentialListList(ListResource): + def __init__(self, version: Version, trunk_sid: str): """ Initialize the CredentialListList @@ -253,54 +391,114 @@ 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 + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "CredentialListSid": credential_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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( { "CredentialListSid": credential_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -351,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, @@ -370,6 +618,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -396,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( @@ -404,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, @@ -428,8 +728,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return CredentialListPage(self._version, response, self._solution) + 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 CredentialListPage(self._version, response, solution=self._solution) async def page_async( self, @@ -455,10 +761,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return CredentialListPage(self._version, response, self._solution) + 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: """ @@ -470,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: """ @@ -482,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 e528e0b1c3..49c56e5cbc 100644 --- a/twilio/rest/trunking/v1/trunk/ip_access_control_list.py +++ b/twilio/rest/trunking/v1/trunk/ip_access_control_list.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class IpAccessControlListInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IpAccessControlList resource. :ivar sid: The unique string that we created to identify the IpAccessControlList resource. @@ -60,6 +59,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[IpAccessControlListContext] = None @property @@ -96,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 @@ -114,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 @@ -125,6 +161,7 @@ def __repr__(self) -> str: class IpAccessControlListContext(InstanceContext): + def __init__(self, version: Version, trunk_sid: str, sid: str): """ Initialize the IpAccessControlListContext @@ -144,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 @@ -151,9 +202,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -163,9 +236,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpAccessControlListInstance 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) -> IpAccessControlListInstance: @@ -175,18 +272,45 @@ def fetch(self) -> IpAccessControlListInstance: :returns: The fetched IpAccessControlListInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], ) - return IpAccessControlListInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpAccessControlListInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> IpAccessControlListInstance: """ @@ -195,18 +319,29 @@ async def fetch_async(self) -> IpAccessControlListInstance: :returns: The fetched IpAccessControlListInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return IpAccessControlListInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], ) - return IpAccessControlListInstance( + 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: """ @@ -219,12 +354,14 @@ def __repr__(self) -> str: class IpAccessControlListPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> IpAccessControlListInstance: """ Build an instance of IpAccessControlListInstance :param payload: Payload response from the API """ + return IpAccessControlListInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -239,6 +376,7 @@ def __repr__(self) -> str: class IpAccessControlListList(ListResource): + def __init__(self, version: Version, trunk_sid: str): """ Initialize the IpAccessControlListList @@ -255,6 +393,29 @@ 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) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "IpAccessControlListSid": ip_access_control_list_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, ip_access_control_list_sid: str) -> IpAccessControlListInstance: """ Create the IpAccessControlListInstance @@ -263,20 +424,50 @@ def create(self, ip_access_control_list_sid: str) -> IpAccessControlListInstance :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"] + ) + + def create_with_http_info(self, ip_access_control_list_sid: str) -> ApiResponse: + """ + 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 = 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( { "IpAccessControlListSid": ip_access_control_list_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return IpAccessControlListInstance( - self._version, payload, trunk_sid=self._solution["trunk_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( @@ -289,21 +480,30 @@ async def create_async( :returns: The created IpAccessControlListInstance """ - data = values.of( - { - "IpAccessControlListSid": ip_access_control_list_sid, - } + payload, _, _ = await self._create_async( + ip_access_control_list_sid=ip_access_control_list_sid ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return IpAccessControlListInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - return IpAccessControlListInstance( + 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, @@ -355,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, @@ -374,6 +624,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -400,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( @@ -408,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, @@ -432,8 +734,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return IpAccessControlListPage(self._version, response, self._solution) + 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 IpAccessControlListPage(self._version, response, solution=self._solution) async def page_async( self, @@ -459,10 +767,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return IpAccessControlListPage(self._version, response, self._solution) + 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: """ @@ -474,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: """ @@ -486,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 79dca9387b..4ac87498f8 100644 --- a/twilio/rest/trunking/v1/trunk/origination_url.py +++ b/twilio/rest/trunking/v1/trunk/origination_url.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class OriginationUrlInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the OriginationUrl resource. :ivar sid: The unique string that we created to identify the OriginationUrl resource. @@ -68,6 +67,7 @@ def __init__( "trunk_sid": trunk_sid, "sid": sid or self.sid, } + self._context: Optional[OriginationUrlContext] = None @property @@ -104,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 @@ -122,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, @@ -176,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 @@ -187,6 +277,7 @@ def __repr__(self) -> str: class OriginationUrlContext(InstanceContext): + def __init__(self, version: Version, trunk_sid: str, sid: str): """ Initialize the OriginationUrlContext @@ -204,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 @@ -211,9 +316,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -223,9 +350,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the OriginationUrlInstance 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) -> OriginationUrlInstance: @@ -235,18 +386,45 @@ def fetch(self) -> OriginationUrlInstance: :returns: The fetched OriginationUrlInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], ) - return OriginationUrlInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the OriginationUrlInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> OriginationUrlInstance: """ @@ -255,54 +433,90 @@ async def fetch_async(self) -> OriginationUrlInstance: :returns: The fetched OriginationUrlInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return OriginationUrlInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], ) - return OriginationUrlInstance( + 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( + 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 - - :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. + Internal helper for update operation - :returns: The updated OriginationUrlInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Weight": weight, "Priority": priority, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "FriendlyName": friendly_name, "SipUrl": sip_url, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -310,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. @@ -327,24 +541,83 @@ 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( { "Weight": weight, "Priority": priority, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "FriendlyName": friendly_name, "SipUrl": sip_url, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -352,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 @@ -363,12 +670,14 @@ def __repr__(self) -> str: class OriginationUrlPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> OriginationUrlInstance: """ Build an instance of OriginationUrlInstance :param payload: Payload response from the API """ + return OriginationUrlInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -383,6 +692,7 @@ def __repr__(self) -> str: class OriginationUrlList(ListResource): + def __init__(self, version: Version, trunk_sid: str): """ Initialize the OriginationUrlList @@ -399,6 +709,40 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/OriginationUrls".format(**self._solution) + def _create( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Weight": weight, + "Priority": priority, + "Enabled": serialize.boolean_to_string(enabled), + "FriendlyName": friendly_name, + "SipUrl": sip_url, + } + ) + 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, weight: int, @@ -418,24 +762,80 @@ def create( :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"] + ) + + def create_with_http_info( + self, + weight: int, + priority: int, + enabled: bool, + friendly_name: str, + sip_url: str, + ) -> ApiResponse: + """ + 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 = 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( { "Weight": weight, "Priority": priority, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "FriendlyName": friendly_name, "SipUrl": sip_url, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return OriginationUrlInstance( - self._version, payload, trunk_sid=self._solution["trunk_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( @@ -457,25 +857,47 @@ async def create_async( :returns: The created OriginationUrlInstance """ - data = values.of( - { - "Weight": weight, - "Priority": priority, - "Enabled": enabled, - "FriendlyName": friendly_name, - "SipUrl": sip_url, - } + payload, _, _ = await self._create_async( + weight=weight, + priority=priority, + enabled=enabled, + friendly_name=friendly_name, + sip_url=sip_url, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return OriginationUrlInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - return OriginationUrlInstance( + 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, @@ -527,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, @@ -546,6 +1018,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -572,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( @@ -580,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, @@ -604,8 +1128,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return OriginationUrlPage(self._version, response, self._solution) + 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 OriginationUrlPage(self._version, response, solution=self._solution) async def page_async( self, @@ -631,10 +1161,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return OriginationUrlPage(self._version, response, self._solution) + 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: """ @@ -646,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: """ @@ -658,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 98f53c408f..20abc377fb 100644 --- a/twilio/rest/trunking/v1/trunk/phone_number.py +++ b/twilio/rest/trunking/v1/trunk/phone_number.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class PhoneNumberInstance(InstanceResource): + class AddressRequirement(object): NONE = "none" ANY = "any" @@ -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 @@ -174,6 +212,7 @@ def __repr__(self) -> str: class PhoneNumberContext(InstanceContext): + def __init__(self, version: Version, trunk_sid: str, sid: str): """ Initialize the PhoneNumberContext @@ -191,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 @@ -198,9 +251,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -210,9 +285,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the PhoneNumberInstance 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) -> PhoneNumberInstance: @@ -222,18 +321,45 @@ def fetch(self) -> PhoneNumberInstance: :returns: The fetched PhoneNumberInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], ) - return PhoneNumberInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> PhoneNumberInstance: """ @@ -242,18 +368,29 @@ async def fetch_async(self) -> PhoneNumberInstance: :returns: The fetched PhoneNumberInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return PhoneNumberInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], + sid=self._solution["sid"], ) - return PhoneNumberInstance( + 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: """ @@ -266,12 +403,14 @@ def __repr__(self) -> str: class PhoneNumberPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> PhoneNumberInstance: """ Build an instance of PhoneNumberInstance :param payload: Payload response from the API """ + return PhoneNumberInstance( self._version, payload, trunk_sid=self._solution["trunk_sid"] ) @@ -286,6 +425,7 @@ def __repr__(self) -> str: class PhoneNumberList(ListResource): + def __init__(self, version: Version, trunk_sid: str): """ Initialize the PhoneNumberList @@ -302,54 +442,108 @@ 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 - - :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. + Internal helper for create operation - :returns: The created PhoneNumberInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "PhoneNumberSid": phone_number_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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_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( { "PhoneNumberSid": phone_number_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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_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, @@ -400,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, @@ -419,6 +663,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -445,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( @@ -453,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, @@ -477,8 +773,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return PhoneNumberPage(self._version, response, self._solution) + 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 PhoneNumberPage(self._version, response, solution=self._solution) async def page_async( self, @@ -504,10 +806,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return PhoneNumberPage(self._version, response, self._solution) + 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: """ @@ -519,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: """ @@ -531,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 02d9ca290d..5e29ae8205 100644 --- a/twilio/rest/trunking/v1/trunk/recording.py +++ b/twilio/rest/trunking/v1/trunk/recording.py @@ -12,9 +12,9 @@ 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 @@ -22,6 +22,7 @@ class RecordingInstance(InstanceResource): + class RecordingMode(object): DO_NOT_RECORD = "do-not-record" RECORD_FROM_RINGING = "record-from-ringing" @@ -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 @@ -129,6 +185,7 @@ def __repr__(self) -> str: class RecordingContext(InstanceContext): + def __init__(self, version: Version, trunk_sid: str): """ Initialize the RecordingContext @@ -144,6 +201,22 @@ def __init__(self, version: Version, trunk_sid: str): } self._uri = "/Trunks/{trunk_sid}/Recording".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) -> RecordingInstance: """ Fetch the RecordingInstance @@ -151,17 +224,43 @@ def fetch(self) -> RecordingInstance: :returns: The fetched RecordingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], ) - return RecordingInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RecordingInstance: """ @@ -170,17 +269,55 @@ async def fetch_async(self) -> RecordingInstance: :returns: The fetched RecordingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return RecordingInstance( + self._version, + payload, + trunk_sid=self._solution["trunk_sid"], ) - return RecordingInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Mode": mode, + "Trim": trim, + } + ) + 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, @@ -195,21 +332,56 @@ def update( :returns: The updated RecordingInstance """ + payload, _, _ = self._update(mode=mode, trim=trim) + return RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] + ) + + def update_with_http_info( + self, + mode: Union["RecordingInstance.RecordingMode", object] = values.unset, + trim: Union["RecordingInstance.RecordingTrim", object] = values.unset, + ) -> ApiResponse: + """ + Update the RecordingInstance and return response metadata + + :param mode: + :param trim: + + :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( { "Mode": mode, "Trim": trim, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RecordingInstance( - self._version, payload, trunk_sid=self._solution["trunk_sid"] + 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( @@ -225,22 +397,29 @@ async def update_async( :returns: The updated RecordingInstance """ - data = values.of( - { - "Mode": mode, - "Trim": trim, - } + payload, _, _ = await self._update_async(mode=mode, trim=trim) + return RecordingInstance( + self._version, payload, trunk_sid=self._solution["trunk_sid"] ) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return RecordingInstance( + :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: """ @@ -253,6 +432,7 @@ def __repr__(self) -> str: class RecordingList(ListResource): + def __init__(self, version: Version, trunk_sid: str): """ Initialize the RecordingList diff --git a/twilio/rest/trusthub/TrusthubBase.py b/twilio/rest/trusthub/TrusthubBase.py index f58cc7cfec..97fd32f9b7 100644 --- a/twilio/rest/trusthub/TrusthubBase.py +++ b/twilio/rest/trusthub/TrusthubBase.py @@ -17,6 +17,7 @@ class TrusthubBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Trusthub Domain diff --git a/twilio/rest/trusthub/v1/__init__.py b/twilio/rest/trusthub/v1/__init__.py index 76692aee0d..596c5ea758 100644 --- a/twilio/rest/trusthub/v1/__init__.py +++ b/twilio/rest/trusthub/v1/__init__.py @@ -15,6 +15,13 @@ from typing import Optional from twilio.base.version import Version from twilio.base.domain import Domain +from twilio.rest.trusthub.v1.compliance_inquiries import ComplianceInquiriesList +from twilio.rest.trusthub.v1.compliance_registration_inquiries import ( + ComplianceRegistrationInquiriesList, +) +from twilio.rest.trusthub.v1.compliance_tollfree_inquiries import ( + ComplianceTollfreeInquiriesList, +) from twilio.rest.trusthub.v1.customer_profiles import CustomerProfilesList from twilio.rest.trusthub.v1.end_user import EndUserList from twilio.rest.trusthub.v1.end_user_type import EndUserTypeList @@ -25,6 +32,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Trusthub @@ -32,6 +40,13 @@ def __init__(self, domain: Domain): :param domain: The Twilio.trusthub domain """ super().__init__(domain, "v1") + self._compliance_inquiries: Optional[ComplianceInquiriesList] = None + self._compliance_registration_inquiries: Optional[ + ComplianceRegistrationInquiriesList + ] = None + self._compliance_tollfree_inquiries: Optional[ + ComplianceTollfreeInquiriesList + ] = None self._customer_profiles: Optional[CustomerProfilesList] = None self._end_users: Optional[EndUserList] = None self._end_user_types: Optional[EndUserTypeList] = None @@ -40,6 +55,26 @@ def __init__(self, domain: Domain): self._supporting_document_types: Optional[SupportingDocumentTypeList] = None self._trust_products: Optional[TrustProductsList] = None + @property + def compliance_inquiries(self) -> ComplianceInquiriesList: + if self._compliance_inquiries is None: + self._compliance_inquiries = ComplianceInquiriesList(self) + return self._compliance_inquiries + + @property + def compliance_registration_inquiries(self) -> ComplianceRegistrationInquiriesList: + if self._compliance_registration_inquiries is None: + self._compliance_registration_inquiries = ( + ComplianceRegistrationInquiriesList(self) + ) + return self._compliance_registration_inquiries + + @property + def compliance_tollfree_inquiries(self) -> ComplianceTollfreeInquiriesList: + if self._compliance_tollfree_inquiries is None: + self._compliance_tollfree_inquiries = ComplianceTollfreeInquiriesList(self) + return self._compliance_tollfree_inquiries + @property def customer_profiles(self) -> CustomerProfilesList: if self._customer_profiles is None: diff --git a/twilio/rest/trusthub/v1/compliance_inquiries.py b/twilio/rest/trusthub/v1/compliance_inquiries.py new file mode 100644 index 0000000000..107749eaa4 --- /dev/null +++ b/twilio/rest/trusthub/v1/compliance_inquiries.py @@ -0,0 +1,480 @@ +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, 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 ComplianceInquiriesInstance(InstanceResource): + """ + :ivar inquiry_id: The unique ID used to start an embedded compliance registration session. + :ivar inquiry_session_token: The session token used to start an embedded compliance registration session. + :ivar customer_id: The CustomerID matching the Customer Profile that should be resumed or resubmitted for editing. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + customer_id: Optional[str] = None, + ): + super().__init__(version) + + self.inquiry_id: Optional[str] = payload.get("inquiry_id") + self.inquiry_session_token: Optional[str] = payload.get("inquiry_session_token") + self.customer_id: Optional[str] = payload.get("customer_id") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "customer_id": customer_id or self.customer_id, + } + + self._context: Optional[ComplianceInquiriesContext] = None + + @property + def _proxy(self) -> "ComplianceInquiriesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ComplianceInquiriesContext for this ComplianceInquiriesInstance + """ + if self._context is None: + self._context = ComplianceInquiriesContext( + self._version, + customer_id=self._solution["customer_id"], + ) + return self._context + + 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 + """ + return self._proxy.update( + primary_profile_sid=primary_profile_sid, + theme_set_id=theme_set_id, + ) + + 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 + """ + return await self._proxy.update_async( + primary_profile_sid=primary_profile_sid, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ComplianceInquiriesContext(InstanceContext): + + def __init__(self, version: Version, customer_id: str): + """ + Initialize the ComplianceInquiriesContext + + :param version: Version that contains the resource + :param customer_id: The unique CustomerId matching the Customer Profile/Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Compliance Inquiry creation call. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "customer_id": customer_id, + } + self._uri = "/ComplianceInquiries/Customers/{customer_id}/Initialize".format( + **self._solution + ) + + def _update( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "PrimaryProfileSid": primary_profile_sid, + "ThemeSetId": theme_set_id, + } + ) + 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, 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"] + ) + + def update_with_http_info( + self, primary_profile_sid: str, theme_set_id: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( + { + "PrimaryProfileSid": primary_profile_sid, + "ThemeSetId": theme_set_id, + } + ) + 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, 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format(context) + + +class ComplianceInquiriesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ComplianceInquiriesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ComplianceInquiries/Customers/Initialize" + + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + "PrimaryProfileSid": primary_profile_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, + notification_email: Union[str, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + primary_profile_sid: Union[str, object] = values.unset, + ) -> ComplianceInquiriesInstance: + """ + 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, _, _ = 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( + { + "NotificationEmail": notification_email, + "ThemeSetId": theme_set_id, + "PrimaryProfileSid": primary_profile_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, + 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 + + :param customer_id: The unique CustomerId matching the Customer Profile/Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Compliance Inquiry creation call. + """ + return ComplianceInquiriesContext(self._version, customer_id=customer_id) + + def __call__(self, customer_id: str) -> ComplianceInquiriesContext: + """ + Constructs a ComplianceInquiriesContext + + :param customer_id: The unique CustomerId matching the Customer Profile/Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Compliance Inquiry creation call. + """ + return ComplianceInquiriesContext(self._version, customer_id=customer_id) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/trusthub/v1/compliance_registration_inquiries.py b/twilio/rest/trusthub/v1/compliance_registration_inquiries.py new file mode 100644 index 0000000000..5c5a96de06 --- /dev/null +++ b/twilio/rest/trusthub/v1/compliance_registration_inquiries.py @@ -0,0 +1,1147 @@ +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, 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 ComplianceRegistrationInquiriesInstance(InstanceResource): + + class BusinessIdentityType(object): + DIRECT_CUSTOMER = "direct_customer" + ISV_RESELLER_OR_PARTNER = "isv_reseller_or_partner" + UNKNOWN = "unknown" + + class BusinessRegistrationAuthority(object): + UK_CRN = "UK:CRN" + US_EIN = "US:EIN" + CA_CBN = "CA:CBN" + AU_ACN = "AU:ACN" + OTHER = "Other" + + class EndUserType(object): + INDIVIDUAL = "Individual" + BUSINESS = "Business" + + class PhoneNumberType(object): + LOCAL = "local" + NATIONAL = "national" + MOBILE = "mobile" + TOLL_FREE = "toll-free" + + """ + :ivar inquiry_id: The unique ID used to start an embedded compliance registration session. + :ivar inquiry_session_token: The session token used to start an embedded compliance registration session. + :ivar registration_id: The RegistrationId matching the Registration Profile that should be resumed or resubmitted for editing. + :ivar url: The URL of this resource. + """ + + def __init__( + self, + version: Version, + payload: Dict[str, Any], + registration_id: Optional[str] = None, + ): + super().__init__(version) + + self.inquiry_id: Optional[str] = payload.get("inquiry_id") + self.inquiry_session_token: Optional[str] = payload.get("inquiry_session_token") + self.registration_id: Optional[str] = payload.get("registration_id") + self.url: Optional[str] = payload.get("url") + + self._solution = { + "registration_id": registration_id or self.registration_id, + } + + self._context: Optional[ComplianceRegistrationInquiriesContext] = None + + @property + def _proxy(self) -> "ComplianceRegistrationInquiriesContext": + """ + Generate an instance context for the instance, the context is capable of + performing various actions. All instance actions are proxied to the context + + :returns: ComplianceRegistrationInquiriesContext for this ComplianceRegistrationInquiriesInstance + """ + if self._context is None: + self._context = ComplianceRegistrationInquiriesContext( + self._version, + registration_id=self._solution["registration_id"], + ) + return self._context + + 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 + """ + return self._proxy.update( + is_isv_embed=is_isv_embed, + theme_set_id=theme_set_id, + ) + + 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 + """ + return await self._proxy.update_async( + is_isv_embed=is_isv_embed, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class ComplianceRegistrationInquiriesContext(InstanceContext): + + def __init__(self, version: Version, registration_id: str): + """ + Initialize the ComplianceRegistrationInquiriesContext + + :param version: Version that contains the resource + :param registration_id: The unique RegistrationId matching the Regulatory Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Regulatory Compliance Inquiry creation call. + """ + super().__init__(version) + + # Path Solution + self._solution = { + "registration_id": registration_id, + } + self._uri = "/ComplianceInquiries/Registration/{registration_id}/RegulatoryCompliance/GB/Initialize".format( + **self._solution + ) + + def _update( + self, + is_isv_embed: Union[bool, object] = values.unset, + theme_set_id: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "ThemeSetId": theme_set_id, + } + ) + 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, + 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"] + ) + + 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 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 = 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( + { + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "ThemeSetId": theme_set_id, + } + ) + 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, + 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 + + :returns: Machine friendly representation + """ + context = " ".join("{}={}".format(k, v) for k, v in self._solution.items()) + return "".format( + context + ) + + +class ComplianceRegistrationInquiriesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ComplianceRegistrationInquiriesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = ( + "/ComplianceInquiries/Registration/RegulatoryCompliance/GB/Initialize" + ) + + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "EndUserType": end_user_type, + "PhoneNumberType": phone_number_type, + "BusinessIdentityType": business_identity_type, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessLegalName": business_legal_name, + "NotificationEmail": notification_email, + "AcceptedNotificationReceipt": serialize.boolean_to_string( + accepted_notification_receipt + ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessWebsiteUrl": business_website_url, + "FriendlyName": friendly_name, + "AuthorizedRepresentative1FirstName": authorized_representative1_first_name, + "AuthorizedRepresentative1LastName": authorized_representative1_last_name, + "AuthorizedRepresentative1Phone": authorized_representative1_phone, + "AuthorizedRepresentative1Email": authorized_representative1_email, + "AuthorizedRepresentative1DateOfBirth": authorized_representative1_date_of_birth, + "AddressStreet": address_street, + "AddressStreetSecondary": address_street_secondary, + "AddressCity": address_city, + "AddressSubdivision": address_subdivision, + "AddressPostalCode": address_postal_code, + "AddressCountryCode": address_country_code, + "EmergencyAddressStreet": emergency_address_street, + "EmergencyAddressStreetSecondary": emergency_address_street_secondary, + "EmergencyAddressCity": emergency_address_city, + "EmergencyAddressSubdivision": emergency_address_subdivision, + "EmergencyAddressPostalCode": emergency_address_postal_code, + "EmergencyAddressCountryCode": emergency_address_country_code, + "UseAddressAsEmergencyAddress": serialize.boolean_to_string( + use_address_as_emergency_address + ), + "FileName": file_name, + "File": file, + "FirstName": first_name, + "LastName": last_name, + "DateOfBirth": date_of_birth, + "IndividualEmail": individual_email, + "IndividualPhone": individual_phone, + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "IsvRegisteringForSelfOrTenant": isv_registering_for_self_or_tenant, + "StatusCallbackUrl": status_callback_url, + "ThemeSetId": theme_set_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, + 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: + """ + 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, _, _ = 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( + { + "EndUserType": end_user_type, + "PhoneNumberType": phone_number_type, + "BusinessIdentityType": business_identity_type, + "BusinessRegistrationAuthority": business_registration_authority, + "BusinessLegalName": business_legal_name, + "NotificationEmail": notification_email, + "AcceptedNotificationReceipt": serialize.boolean_to_string( + accepted_notification_receipt + ), + "BusinessRegistrationNumber": business_registration_number, + "BusinessWebsiteUrl": business_website_url, + "FriendlyName": friendly_name, + "AuthorizedRepresentative1FirstName": authorized_representative1_first_name, + "AuthorizedRepresentative1LastName": authorized_representative1_last_name, + "AuthorizedRepresentative1Phone": authorized_representative1_phone, + "AuthorizedRepresentative1Email": authorized_representative1_email, + "AuthorizedRepresentative1DateOfBirth": authorized_representative1_date_of_birth, + "AddressStreet": address_street, + "AddressStreetSecondary": address_street_secondary, + "AddressCity": address_city, + "AddressSubdivision": address_subdivision, + "AddressPostalCode": address_postal_code, + "AddressCountryCode": address_country_code, + "EmergencyAddressStreet": emergency_address_street, + "EmergencyAddressStreetSecondary": emergency_address_street_secondary, + "EmergencyAddressCity": emergency_address_city, + "EmergencyAddressSubdivision": emergency_address_subdivision, + "EmergencyAddressPostalCode": emergency_address_postal_code, + "EmergencyAddressCountryCode": emergency_address_country_code, + "UseAddressAsEmergencyAddress": serialize.boolean_to_string( + use_address_as_emergency_address + ), + "FileName": file_name, + "File": file, + "FirstName": first_name, + "LastName": last_name, + "DateOfBirth": date_of_birth, + "IndividualEmail": individual_email, + "IndividualPhone": individual_phone, + "IsIsvEmbed": serialize.boolean_to_string(is_isv_embed), + "IsvRegisteringForSelfOrTenant": isv_registering_for_self_or_tenant, + "StatusCallbackUrl": status_callback_url, + "ThemeSetId": theme_set_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, + 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 + + :param registration_id: The unique RegistrationId matching the Regulatory Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Regulatory Compliance Inquiry creation call. + """ + return ComplianceRegistrationInquiriesContext( + self._version, registration_id=registration_id + ) + + def __call__(self, registration_id: str) -> ComplianceRegistrationInquiriesContext: + """ + Constructs a ComplianceRegistrationInquiriesContext + + :param registration_id: The unique RegistrationId matching the Regulatory Compliance Inquiry that should be resumed or resubmitted. This value will have been returned by the initial Regulatory Compliance Inquiry creation call. + """ + return ComplianceRegistrationInquiriesContext( + self._version, registration_id=registration_id + ) + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py b/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py new file mode 100644 index 0000000000..691594bd4f --- /dev/null +++ b/twilio/rest/trusthub/v1/compliance_tollfree_inquiries.py @@ -0,0 +1,822 @@ +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, 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 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" + PAPER_FORM = "PAPER_FORM" + VIA_TEXT = "VIA_TEXT" + MOBILE_QR_CODE = "MOBILE_QR_CODE" + + """ + :ivar inquiry_id: The unique ID used to start an embedded compliance registration session. + :ivar inquiry_session_token: The session token used to start an embedded compliance registration session. + :ivar registration_id: The TolfreeId matching the Tollfree Profile that should be resumed or resubmitted for editing. + :ivar url: The URL of this resource. + """ + + def __init__(self, version: Version, payload: Dict[str, Any]): + super().__init__(version) + + self.inquiry_id: Optional[str] = payload.get("inquiry_id") + self.inquiry_session_token: Optional[str] = payload.get("inquiry_session_token") + self.registration_id: Optional[str] = payload.get("registration_id") + self.url: Optional[str] = payload.get("url") + + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + + return "" + + +class ComplianceTollfreeInquiriesList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ComplianceTollfreeInquiriesList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ComplianceInquiries/Tollfree/Initialize" + + 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, + 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 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), + "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, + "ThemeSetId": theme_set_id, + "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"}) + + 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, + 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: + """ + 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, _, _ = 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), + "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, + "ThemeSetId": theme_set_id, + "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"}) + + 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, + 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 + + :returns: Machine friendly representation + """ + return "" diff --git a/twilio/rest/trusthub/v1/customer_profiles/__init__.py b/twilio/rest/trusthub/v1/customer_profiles/__init__.py index a82fafa4da..5ba9df5ecb 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/__init__.py +++ b/twilio/rest/trusthub/v1/customer_profiles/__init__.py @@ -12,10 +12,10 @@ 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 @@ -33,6 +33,7 @@ class CustomerProfilesInstance(InstanceResource): + class Status(object): DRAFT = "draft" PENDING_REVIEW = "pending-review" @@ -53,6 +54,7 @@ class Status(object): :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 Customer-Profile resource. :ivar links: The URLs of the Assigned Items of the Customer-Profile resource. + :ivar errors: The error codes associated with the rejection of the Customer-Profile. """ def __init__( @@ -78,10 +80,12 @@ def __init__( ) self.url: Optional[str] = payload.get("url") self.links: Optional[Dict[str, object]] = payload.get("links") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") self._solution = { "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesContext] = None @property @@ -117,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 @@ -135,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, @@ -183,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, @@ -219,6 +307,7 @@ def __repr__(self) -> str: class CustomerProfilesContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CustomerProfilesContext @@ -244,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 @@ -251,9 +354,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -263,9 +388,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesInstance 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) -> CustomerProfilesInstance: @@ -275,17 +424,43 @@ def fetch(self) -> CustomerProfilesInstance: :returns: The fetched CustomerProfilesInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CustomerProfilesInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CustomerProfilesInstance: """ @@ -294,17 +469,59 @@ async def fetch_async(self) -> CustomerProfilesInstance: :returns: The fetched CustomerProfilesInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CustomerProfilesInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CustomerProfilesInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + 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, @@ -323,6 +540,58 @@ def update( :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"] + ) + + 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 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 = 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( { "Status": status, @@ -331,15 +600,14 @@ def update( "Email": email, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CustomerProfilesInstance( - self._version, payload, sid=self._solution["sid"] + 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( @@ -359,24 +627,43 @@ async def update_async( :returns: The updated CustomerProfilesInstance """ - data = values.of( - { - "Status": status, - "StatusCallback": status_callback, - "FriendlyName": friendly_name, - "Email": email, - } + payload, _, _ = await self._update_async( + status=status, + status_callback=status_callback, + friendly_name=friendly_name, + email=email, ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return CustomerProfilesInstance( + self._version, payload, sid=self._solution["sid"] ) - return CustomerProfilesInstance( + 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( @@ -433,12 +720,14 @@ def __repr__(self) -> str: class CustomerProfilesPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CustomerProfilesInstance: """ Build an instance of CustomerProfilesInstance :param payload: Payload response from the API """ + return CustomerProfilesInstance(self._version, payload) def __repr__(self) -> str: @@ -451,6 +740,7 @@ def __repr__(self) -> str: class CustomerProfilesList(ListResource): + def __init__(self, version: Version): """ Initialize the CustomerProfilesList @@ -462,6 +752,38 @@ def __init__(self, version: Version): self._uri = "/CustomerProfiles" + def _create( + self, + friendly_name: str, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Email": email, + "PolicySid": policy_sid, + "StatusCallback": status_callback, + } + ) + 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, @@ -479,6 +801,54 @@ def create( :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( { "FriendlyName": friendly_name, @@ -487,14 +857,15 @@ def create( "StatusCallback": status_callback, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CustomerProfilesInstance(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, @@ -513,22 +884,39 @@ async def create_async( :returns: The created CustomerProfilesInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Email": email, - "PolicySid": policy_sid, - "StatusCallback": status_callback, - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + email=email, + policy_sid=policy_sid, + status_callback=status_callback, ) + return CustomerProfilesInstance(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, + email: str, + policy_sid: str, + status_callback: Union[str, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the CustomerProfilesInstance and return response metadata - return CustomerProfilesInstance(self._version, payload) + :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, @@ -602,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, @@ -627,6 +1085,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -662,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( @@ -673,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, @@ -706,7 +1234,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CustomerProfilesPage(self._version, response) async def page_async( @@ -742,11 +1276,103 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 e1905c1ac5..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class CustomerProfilesChannelEndpointAssignmentInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Item Assignment resource. :ivar customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. @@ -58,6 +57,7 @@ def __init__( "customer_profile_sid": customer_profile_sid, "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesChannelEndpointAssignmentContext] = None @property @@ -94,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 @@ -112,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 @@ -125,6 +161,7 @@ def __repr__(self) -> str: class CustomerProfilesChannelEndpointAssignmentContext(InstanceContext): + def __init__(self, version: Version, customer_profile_sid: str, sid: str): """ Initialize the CustomerProfilesChannelEndpointAssignmentContext @@ -144,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 @@ -151,9 +202,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -163,9 +236,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesChannelEndpointAssignmentInstance 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) -> CustomerProfilesChannelEndpointAssignmentInstance: @@ -175,18 +272,45 @@ def fetch(self) -> CustomerProfilesChannelEndpointAssignmentInstance: :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], ) - return CustomerProfilesChannelEndpointAssignmentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesChannelEndpointAssignmentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CustomerProfilesChannelEndpointAssignmentInstance: """ @@ -195,18 +319,29 @@ async def fetch_async(self) -> CustomerProfilesChannelEndpointAssignmentInstance :returns: The fetched CustomerProfilesChannelEndpointAssignmentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CustomerProfilesChannelEndpointAssignmentInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], ) - return CustomerProfilesChannelEndpointAssignmentInstance( + 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: """ @@ -221,6 +356,7 @@ def __repr__(self) -> str: class CustomerProfilesChannelEndpointAssignmentPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> CustomerProfilesChannelEndpointAssignmentInstance: @@ -229,6 +365,7 @@ def get_instance( :param payload: Payload response from the API """ + return CustomerProfilesChannelEndpointAssignmentInstance( self._version, payload, @@ -245,6 +382,7 @@ def __repr__(self) -> str: class CustomerProfilesChannelEndpointAssignmentList(ListResource): + def __init__(self, version: Version, customer_profile_sid: str): """ Initialize the CustomerProfilesChannelEndpointAssignmentList @@ -263,66 +401,142 @@ 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 + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "ChannelEndpointType": channel_endpoint_type, "ChannelEndpointSid": channel_endpoint_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, + 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( { "ChannelEndpointType": channel_endpoint_type, "ChannelEndpointSid": channel_endpoint_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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_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, @@ -389,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, @@ -412,6 +690,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( channel_endpoint_sid=channel_endpoint_sid, @@ -444,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( @@ -454,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, @@ -484,9 +826,15 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CustomerProfilesChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -519,12 +867,102 @@ async def page_async( } ) + 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 + 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 @@ -539,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( @@ -555,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 c318b539cc..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class CustomerProfilesEntityAssignmentsInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Item Assignment resource. :ivar customer_profile_sid: The unique string that we created to identify the CustomerProfile resource. @@ -56,6 +55,7 @@ def __init__( "customer_profile_sid": customer_profile_sid, "sid": sid or self.sid, } + self._context: Optional[CustomerProfilesEntityAssignmentsContext] = None @property @@ -92,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 @@ -110,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 @@ -125,6 +161,7 @@ def __repr__(self) -> str: class CustomerProfilesEntityAssignmentsContext(InstanceContext): + def __init__(self, version: Version, customer_profile_sid: str, sid: str): """ Initialize the CustomerProfilesEntityAssignmentsContext @@ -146,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 @@ -153,9 +204,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -165,9 +238,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CustomerProfilesEntityAssignmentsInstance 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) -> CustomerProfilesEntityAssignmentsInstance: @@ -177,18 +274,45 @@ def fetch(self) -> CustomerProfilesEntityAssignmentsInstance: :returns: The fetched CustomerProfilesEntityAssignmentsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], ) - return CustomerProfilesEntityAssignmentsInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEntityAssignmentsInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CustomerProfilesEntityAssignmentsInstance: """ @@ -197,18 +321,29 @@ async def fetch_async(self) -> CustomerProfilesEntityAssignmentsInstance: :returns: The fetched CustomerProfilesEntityAssignmentsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CustomerProfilesEntityAssignmentsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], ) - return CustomerProfilesEntityAssignmentsInstance( + 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: """ @@ -225,6 +360,7 @@ def __repr__(self) -> str: class CustomerProfilesEntityAssignmentsPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> CustomerProfilesEntityAssignmentsInstance: @@ -233,6 +369,7 @@ def get_instance( :param payload: Payload response from the API """ + return CustomerProfilesEntityAssignmentsInstance( self._version, payload, @@ -249,6 +386,7 @@ def __repr__(self) -> str: class CustomerProfilesEntityAssignmentsList(ListResource): + def __init__(self, version: Version, customer_profile_sid: str): """ Initialize the CustomerProfilesEntityAssignmentsList @@ -267,62 +405,119 @@ 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( { "ObjectSid": object_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "ObjectSid": object_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[CustomerProfilesEntityAssignmentsInstance]: @@ -332,6 +527,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. + :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 @@ -342,12 +538,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(object_type=object_type, page_size=limits["page_size"]) return self._version.stream(page, limits["limit"]) async def stream_async( self, + object_type: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[CustomerProfilesEntityAssignmentsInstance]: @@ -357,6 +554,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. + :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 @@ -367,12 +565,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( + object_type=object_type, page_size=limits["page_size"] + ) 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, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[CustomerProfilesEntityAssignmentsInstance]: @@ -381,6 +638,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :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 @@ -390,8 +648,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( + object_type=object_type, limit=limit, page_size=page_size, ) @@ -399,6 +659,7 @@ def list( async def list_async( self, + object_type: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[CustomerProfilesEntityAssignmentsInstance]: @@ -407,6 +668,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :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 @@ -416,16 +678,75 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( + object_type=object_type, limit=limit, page_size=page_size, ) ] + 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, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -434,6 +755,7 @@ def page( Retrieve a single page of CustomerProfilesEntityAssignmentsInstance records from the API. Request is executed immediately + :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 @@ -442,19 +764,27 @@ def page( """ data = values.of( { + "ObjectType": object_type, "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CustomerProfilesEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_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, @@ -463,6 +793,7 @@ async def page_async( Asynchronously retrieve a single page of CustomerProfilesEntityAssignmentsInstance records from the API. Request is executed immediately + :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 @@ -471,18 +802,103 @@ async def page_async( """ 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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + 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: """ @@ -495,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( @@ -511,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 c3611f7647..7094e1c0f9 100644 --- a/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py +++ b/twilio/rest/trusthub/v1/customer_profiles/customer_profiles_evaluations.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class CustomerProfilesEvaluationsInstance(InstanceResource): + class Status(object): COMPLIANT = "compliant" NONCOMPLIANT = "noncompliant" @@ -52,10 +53,10 @@ def __init__( self.account_sid: Optional[str] = payload.get("account_sid") self.policy_sid: Optional[str] = payload.get("policy_sid") self.customer_profile_sid: Optional[str] = payload.get("customer_profile_sid") - self.status: Optional[ - "CustomerProfilesEvaluationsInstance.Status" - ] = payload.get("status") - self.results: Optional[List[object]] = payload.get("results") + self.status: Optional["CustomerProfilesEvaluationsInstance.Status"] = ( + payload.get("status") + ) + self.results: Optional[List[Dict[str, object]]] = payload.get("results") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -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 @@ -114,6 +134,7 @@ def __repr__(self) -> str: class CustomerProfilesEvaluationsContext(InstanceContext): + def __init__(self, version: Version, customer_profile_sid: str, sid: str): """ Initialize the CustomerProfilesEvaluationsContext @@ -133,6 +154,22 @@ def __init__(self, version: Version, customer_profile_sid: str, sid: str): **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) -> CustomerProfilesEvaluationsInstance: """ Fetch the CustomerProfilesEvaluationsInstance @@ -140,18 +177,45 @@ def fetch(self) -> CustomerProfilesEvaluationsInstance: :returns: The fetched CustomerProfilesEvaluationsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], ) - return CustomerProfilesEvaluationsInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CustomerProfilesEvaluationsInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CustomerProfilesEvaluationsInstance: """ @@ -160,18 +224,29 @@ async def fetch_async(self) -> CustomerProfilesEvaluationsInstance: :returns: The fetched CustomerProfilesEvaluationsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CustomerProfilesEvaluationsInstance( + self._version, + payload, + customer_profile_sid=self._solution["customer_profile_sid"], + sid=self._solution["sid"], ) - return CustomerProfilesEvaluationsInstance( + 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: """ @@ -186,6 +261,7 @@ def __repr__(self) -> str: class CustomerProfilesEvaluationsPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> CustomerProfilesEvaluationsInstance: @@ -194,6 +270,7 @@ def get_instance( :param payload: Payload response from the API """ + return CustomerProfilesEvaluationsInstance( self._version, payload, @@ -210,6 +287,7 @@ def __repr__(self) -> str: class CustomerProfilesEvaluationsList(ListResource): + def __init__(self, version: Version, customer_profile_sid: str): """ Initialize the CustomerProfilesEvaluationsList @@ -228,60 +306,116 @@ 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( { "PolicySid": policy_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, + 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( { "PolicySid": policy_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -332,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, @@ -351,6 +535,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -377,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( @@ -385,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, @@ -409,8 +645,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + 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 CustomerProfilesEvaluationsPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -436,10 +680,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return CustomerProfilesEvaluationsPage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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: """ @@ -451,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: """ @@ -463,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/end_user.py b/twilio/rest/trusthub/v1/end_user.py index 05f096b6c3..bb7c7740b8 100644 --- a/twilio/rest/trusthub/v1/end_user.py +++ b/twilio/rest/trusthub/v1/end_user.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class EndUserInstance(InstanceResource): - """ :ivar sid: The unique string created by Twilio to identify the End User resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the End User resource. @@ -57,6 +56,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserContext] = None @property @@ -92,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 @@ -110,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, @@ -146,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 @@ -157,6 +229,7 @@ def __repr__(self) -> str: class EndUserContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the EndUserContext @@ -172,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 @@ -179,9 +266,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -191,9 +300,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EndUserInstance 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) -> EndUserInstance: @@ -203,17 +336,43 @@ def fetch(self) -> EndUserInstance: :returns: The fetched EndUserInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EndUserInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EndUserInstance: """ @@ -222,17 +381,55 @@ async def fetch_async(self) -> EndUserInstance: :returns: The fetched EndUserInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EndUserInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EndUserInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + 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, @@ -247,20 +444,55 @@ def update( :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( { "FriendlyName": friendly_name, "Attributes": serialize.object(attributes), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -275,20 +507,29 @@ async def update_async( :returns: The updated EndUserInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Attributes": serialize.object(attributes), - } + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes ) + return EndUserInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return EndUserInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -301,12 +542,14 @@ def __repr__(self) -> str: class EndUserPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EndUserInstance: """ Build an instance of EndUserInstance :param payload: Payload response from the API """ + return EndUserInstance(self._version, payload) def __repr__(self) -> str: @@ -319,6 +562,7 @@ def __repr__(self) -> str: class EndUserList(ListResource): + def __init__(self, version: Version): """ Initialize the EndUserList @@ -330,6 +574,36 @@ def __init__(self, version: Version): self._uri = "/EndUsers" + def _create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + 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, @@ -345,6 +619,45 @@ def create( :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( { "FriendlyName": friendly_name, @@ -352,14 +665,15 @@ def create( "Attributes": serialize.object(attributes), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return EndUserInstance(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, @@ -376,21 +690,31 @@ async def create_async( :returns: The created EndUserInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Attributes": serialize.object(attributes), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes ) + return EndUserInstance(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, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the EndUserInstance and return response metadata - return EndUserInstance(self._version, payload) + :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, @@ -442,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, @@ -461,6 +835,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -487,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( @@ -495,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, @@ -519,7 +945,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 EndUserPage(self._version, response) async def page_async( @@ -546,11 +978,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 391012e1ac..8f2da577fb 100644 --- a/twilio/rest/trusthub/v1/end_user_type.py +++ b/twilio/rest/trusthub/v1/end_user_type.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class EndUserTypeInstance(InstanceResource): - """ :ivar sid: The unique string that identifies the End-User Type resource. :ivar friendly_name: A human-readable description that is assigned to describe the End-User Type resource. Examples can include first name, last name, email, business name, etc @@ -40,12 +39,13 @@ def __init__( self.sid: Optional[str] = payload.get("sid") self.friendly_name: Optional[str] = payload.get("friendly_name") self.machine_name: Optional[str] = payload.get("machine_name") - self.fields: Optional[List[object]] = payload.get("fields") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") self.url: Optional[str] = payload.get("url") self._solution = { "sid": sid or self.sid, } + self._context: Optional[EndUserTypeContext] = None @property @@ -81,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 @@ -92,6 +110,7 @@ def __repr__(self) -> str: class EndUserTypeContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the EndUserTypeContext @@ -107,6 +126,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/EndUserTypes/{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) -> EndUserTypeInstance: """ Fetch the EndUserTypeInstance @@ -114,17 +149,43 @@ def fetch(self) -> EndUserTypeInstance: :returns: The fetched EndUserTypeInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EndUserTypeInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EndUserTypeInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EndUserTypeInstance: """ @@ -133,17 +194,27 @@ async def fetch_async(self) -> EndUserTypeInstance: :returns: The fetched EndUserTypeInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EndUserTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return EndUserTypeInstance( + 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: """ @@ -156,12 +227,14 @@ def __repr__(self) -> str: class EndUserTypePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EndUserTypeInstance: """ Build an instance of EndUserTypeInstance :param payload: Payload response from the API """ + return EndUserTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -174,6 +247,7 @@ def __repr__(self) -> str: class EndUserTypeList(ListResource): + def __init__(self, version: Version): """ Initialize the EndUserTypeList @@ -235,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, @@ -254,6 +378,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -280,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( @@ -288,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, @@ -312,7 +488,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 EndUserTypePage(self._version, response) async def page_async( @@ -339,11 +521,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 6c08335216..ed7035da27 100644 --- a/twilio/rest/trusthub/v1/policies.py +++ b/twilio/rest/trusthub/v1/policies.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class PoliciesInstance(InstanceResource): - """ :ivar sid: The unique string that identifies the Policy resource. :ivar friendly_name: A human-readable description that is assigned to describe the Policy resource. Examples can include Primary Customer profile policy @@ -44,6 +43,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[PoliciesContext] = None @property @@ -79,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 @@ -90,6 +108,7 @@ def __repr__(self) -> str: class PoliciesContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the PoliciesContext @@ -105,6 +124,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Policies/{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) -> PoliciesInstance: """ Fetch the PoliciesInstance @@ -112,17 +147,43 @@ def fetch(self) -> PoliciesInstance: :returns: The fetched PoliciesInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return PoliciesInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PoliciesInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> PoliciesInstance: """ @@ -131,17 +192,27 @@ async def fetch_async(self) -> PoliciesInstance: :returns: The fetched PoliciesInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return PoliciesInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return PoliciesInstance( + 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: """ @@ -154,12 +225,14 @@ def __repr__(self) -> str: class PoliciesPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> PoliciesInstance: """ Build an instance of PoliciesInstance :param payload: Payload response from the API """ + return PoliciesInstance(self._version, payload) def __repr__(self) -> str: @@ -172,6 +245,7 @@ def __repr__(self) -> str: class PoliciesList(ListResource): + def __init__(self, version: Version): """ Initialize the PoliciesList @@ -233,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, @@ -252,6 +376,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -278,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( @@ -286,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, @@ -310,7 +486,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 PoliciesPage(self._version, response) async def page_async( @@ -337,11 +519,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 f1f29a4afa..8020232292 100644 --- a/twilio/rest/trusthub/v1/supporting_document.py +++ b/twilio/rest/trusthub/v1/supporting_document.py @@ -12,10 +12,10 @@ 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 @@ -24,13 +24,14 @@ 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 @@ -170,6 +244,7 @@ def __repr__(self) -> str: class SupportingDocumentContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SupportingDocumentContext @@ -185,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 @@ -192,9 +281,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -204,9 +315,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SupportingDocumentInstance 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) -> SupportingDocumentInstance: @@ -216,17 +351,43 @@ def fetch(self) -> SupportingDocumentInstance: :returns: The fetched SupportingDocumentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SupportingDocumentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SupportingDocumentInstance: """ @@ -235,17 +396,55 @@ async def fetch_async(self) -> SupportingDocumentInstance: :returns: The fetched SupportingDocumentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SupportingDocumentInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SupportingDocumentInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Attributes": serialize.object(attributes), + } + ) + 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, @@ -260,21 +459,58 @@ def update( :returns: The updated SupportingDocumentInstance """ + payload, _, _ = self._update(friendly_name=friendly_name, attributes=attributes) + return SupportingDocumentInstance( + 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 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 = 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( { "FriendlyName": friendly_name, "Attributes": serialize.object(attributes), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SupportingDocumentInstance( - self._version, payload, sid=self._solution["sid"] + 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( @@ -290,22 +526,33 @@ async def update_async( :returns: The updated SupportingDocumentInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Attributes": serialize.object(attributes), - } + payload, _, _ = await self._update_async( + friendly_name=friendly_name, attributes=attributes ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + return SupportingDocumentInstance( + self._version, payload, sid=self._solution["sid"] ) - return SupportingDocumentInstance( + 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: """ @@ -318,12 +565,14 @@ def __repr__(self) -> str: class SupportingDocumentPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentInstance: """ Build an instance of SupportingDocumentInstance :param payload: Payload response from the API """ + return SupportingDocumentInstance(self._version, payload) def __repr__(self) -> str: @@ -336,6 +585,7 @@ def __repr__(self) -> str: class SupportingDocumentList(ListResource): + def __init__(self, version: Version): """ Initialize the SupportingDocumentList @@ -347,6 +597,36 @@ def __init__(self, version: Version): self._uri = "/SupportingDocuments" + def _create( + self, + friendly_name: str, + type: str, + attributes: Union[object, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Type": type, + "Attributes": serialize.object(attributes), + } + ) + 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, @@ -362,6 +642,45 @@ def create( :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( { "FriendlyName": friendly_name, @@ -369,14 +688,15 @@ def create( "Attributes": serialize.object(attributes), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SupportingDocumentInstance(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, @@ -393,21 +713,31 @@ async def create_async( :returns: The created SupportingDocumentInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Type": type, - "Attributes": serialize.object(attributes), - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, type=type, attributes=attributes ) + return SupportingDocumentInstance(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, + type: str, + attributes: Union[object, object] = values.unset, + ) -> ApiResponse: + """ + Asynchronously create the SupportingDocumentInstance and return response metadata - return SupportingDocumentInstance(self._version, payload) + :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, @@ -459,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, @@ -478,6 +858,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -504,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( @@ -512,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, @@ -536,7 +968,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SupportingDocumentPage(self._version, response) async def page_async( @@ -563,11 +1001,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 204c0b53a4..2ae6cb345e 100644 --- a/twilio/rest/trusthub/v1/supporting_document_type.py +++ b/twilio/rest/trusthub/v1/supporting_document_type.py @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class SupportingDocumentTypeInstance(InstanceResource): - """ :ivar sid: The unique string that identifies the Supporting Document Type resource. :ivar friendly_name: A human-readable description of the Supporting Document Type resource. @@ -40,12 +39,13 @@ def __init__( self.sid: Optional[str] = payload.get("sid") self.friendly_name: Optional[str] = payload.get("friendly_name") self.machine_name: Optional[str] = payload.get("machine_name") - self.fields: Optional[List[object]] = payload.get("fields") + self.fields: Optional[List[Dict[str, object]]] = payload.get("fields") self.url: Optional[str] = payload.get("url") self._solution = { "sid": sid or self.sid, } + self._context: Optional[SupportingDocumentTypeContext] = None @property @@ -81,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 @@ -92,6 +110,7 @@ def __repr__(self) -> str: class SupportingDocumentTypeContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SupportingDocumentTypeContext @@ -107,6 +126,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/SupportingDocumentTypes/{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) -> SupportingDocumentTypeInstance: """ Fetch the SupportingDocumentTypeInstance @@ -114,17 +149,43 @@ def fetch(self) -> SupportingDocumentTypeInstance: :returns: The fetched SupportingDocumentTypeInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SupportingDocumentTypeInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SupportingDocumentTypeInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SupportingDocumentTypeInstance: """ @@ -133,17 +194,27 @@ async def fetch_async(self) -> SupportingDocumentTypeInstance: :returns: The fetched SupportingDocumentTypeInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SupportingDocumentTypeInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SupportingDocumentTypeInstance( + 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: """ @@ -156,12 +227,14 @@ def __repr__(self) -> str: class SupportingDocumentTypePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SupportingDocumentTypeInstance: """ Build an instance of SupportingDocumentTypeInstance :param payload: Payload response from the API """ + return SupportingDocumentTypeInstance(self._version, payload) def __repr__(self) -> str: @@ -174,6 +247,7 @@ def __repr__(self) -> str: class SupportingDocumentTypeList(ListResource): + def __init__(self, version: Version): """ Initialize the SupportingDocumentTypeList @@ -235,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, @@ -254,6 +378,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -280,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( @@ -288,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, @@ -312,7 +488,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SupportingDocumentTypePage(self._version, response) async def page_async( @@ -339,11 +521,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 627cc5a090..3c2553dbbe 100644 --- a/twilio/rest/trusthub/v1/trust_products/__init__.py +++ b/twilio/rest/trusthub/v1/trust_products/__init__.py @@ -12,10 +12,10 @@ 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 @@ -33,6 +33,7 @@ class TrustProductsInstance(InstanceResource): + class Status(object): DRAFT = "draft" PENDING_REVIEW = "pending-review" @@ -41,18 +42,19 @@ class Status(object): TWILIO_APPROVED = "twilio-approved" """ - :ivar sid: The unique string that we created to identify the Customer-Profile resource. - :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Customer-Profile resource. - :ivar policy_sid: The unique string of a policy that is associated to the Customer-Profile resource. + :ivar sid: The unique string that we created to identify the Trust Product resource. + :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Trust Product resource. + :ivar policy_sid: The unique string of the policy that is associated with the Trust Product resource. :ivar friendly_name: The string that you assigned to describe the resource. :ivar status: - :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 email: The email address that will receive updates when the Customer-Profile resource changes status. + :ivar valid_until: The date and time in GMT in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format until which the resource will be valid. + :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 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 Customer-Profile resource. - :ivar links: The URLs of the Assigned Items of the Customer-Profile resource. + :ivar url: The absolute URL of the Trust Product resource. + :ivar links: The URLs of the Assigned Items of the Trust Product resource. + :ivar errors: The error codes associated with the rejection of the Trust Product. """ def __init__( @@ -78,10 +80,12 @@ def __init__( ) self.url: Optional[str] = payload.get("url") self.links: Optional[Dict[str, object]] = payload.get("links") + self.errors: Optional[List[Dict[str, object]]] = payload.get("errors") self._solution = { "sid": sid or self.sid, } + self._context: Optional[TrustProductsContext] = None @property @@ -117,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 @@ -135,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, @@ -148,7 +188,7 @@ def update( :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. + :param email: The email address that will receive updates when the Trust Product resource changes status. :returns: The updated TrustProductsInstance """ @@ -172,7 +212,7 @@ async def update_async( :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. + :param email: The email address that will receive updates when the Trust Product resource changes status. :returns: The updated TrustProductsInstance """ @@ -183,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, @@ -217,12 +305,13 @@ def __repr__(self) -> str: class TrustProductsContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the TrustProductsContext :param version: Version that contains the resource - :param sid: The unique string that we created to identify the Customer-Profile resource. + :param sid: The unique string that we created to identify the Trust Product resource. """ super().__init__(version) @@ -240,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 @@ -247,9 +350,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -259,9 +384,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsInstance 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) -> TrustProductsInstance: @@ -271,17 +420,43 @@ def fetch(self) -> TrustProductsInstance: :returns: The fetched TrustProductsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return TrustProductsInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TrustProductsInstance: """ @@ -290,17 +465,59 @@ async def fetch_async(self) -> TrustProductsInstance: :returns: The fetched TrustProductsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TrustProductsInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return TrustProductsInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Status": status, + "StatusCallback": status_callback, + "FriendlyName": friendly_name, + "Email": email, + } + ) + 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, @@ -315,10 +532,60 @@ def update( :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. + :param email: The email address that will receive updates when the Trust Product resource changes status. :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( { "Status": status, @@ -327,14 +594,15 @@ def update( "Email": email, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -349,26 +617,45 @@ async def update_async( :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. + :param email: The email address that will receive updates when the Trust Product resource changes status. :returns: The updated TrustProductsInstance """ - data = values.of( - { - "Status": status, - "StatusCallback": status_callback, - "FriendlyName": friendly_name, - "Email": email, - } + 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"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return TrustProductsInstance(self._version, payload, sid=self._solution["sid"]) + :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( @@ -423,12 +710,14 @@ def __repr__(self) -> str: class TrustProductsPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TrustProductsInstance: """ Build an instance of TrustProductsInstance :param payload: Payload response from the API """ + return TrustProductsInstance(self._version, payload) def __repr__(self) -> str: @@ -441,6 +730,7 @@ def __repr__(self) -> str: class TrustProductsList(ListResource): + def __init__(self, version: Version): """ Initialize the TrustProductsList @@ -452,23 +742,20 @@ 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 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 TrustProductsInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -477,16 +764,17 @@ def create( "StatusCallback": status_callback, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return TrustProductsInstance(self._version, payload) + headers["Accept"] = "application/json" - async def create_async( + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( self, friendly_name: str, email: str, @@ -494,15 +782,63 @@ 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 Customer-Profile resource changes status. - :param policy_sid: The unique string of a policy that is associated to the Customer-Profile 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, _, _ = 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( { "FriendlyName": friendly_name, @@ -511,15 +847,67 @@ async def create_async( "StatusCallback": status_callback, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -534,9 +922,9 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "TrustProductsInstance.Status" status: The verification status of the Customer-Profile resource. + :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 Customer-Profile 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 @@ -570,9 +958,9 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param "TrustProductsInstance.Status" status: The verification status of the Customer-Profile resource. + :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 Customer-Profile 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 @@ -592,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, @@ -605,9 +1063,9 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "TrustProductsInstance.Status" status: The verification status of the Customer-Profile resource. + :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 Customer-Profile 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 @@ -617,6 +1075,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -640,9 +1099,9 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param "TrustProductsInstance.Status" status: The verification status of the Customer-Profile resource. + :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 Customer-Profile 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 @@ -652,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( @@ -663,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, @@ -676,9 +1204,9 @@ def page( Retrieve a single page of TrustProductsInstance records from the API. Request is executed immediately - :param status: The verification status of the Customer-Profile resource. + :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 Customer-Profile 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 @@ -696,7 +1224,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 TrustProductsPage(self._version, response) async def page_async( @@ -712,9 +1246,9 @@ async def page_async( Asynchronously retrieve a single page of TrustProductsInstance records from the API. Request is executed immediately - :param status: The verification status of the Customer-Profile resource. + :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 Customer-Profile 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 @@ -732,11 +1266,103 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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. @@ -765,7 +1391,7 @@ def get(self, sid: str) -> TrustProductsContext: """ Constructs a TrustProductsContext - :param sid: The unique string that we created to identify the Customer-Profile resource. + :param sid: The unique string that we created to identify the Trust Product resource. """ return TrustProductsContext(self._version, sid=sid) @@ -773,7 +1399,7 @@ def __call__(self, sid: str) -> TrustProductsContext: """ Constructs a TrustProductsContext - :param sid: The unique string that we created to identify the Customer-Profile resource. + :param sid: The unique string that we created to identify the Trust Product resource. """ return TrustProductsContext(self._version, sid=sid) 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 42b5923e6f..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class TrustProductsChannelEndpointAssignmentInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Item Assignment resource. :ivar trust_product_sid: The unique string that we created to identify the CustomerProfile resource. @@ -58,6 +57,7 @@ def __init__( "trust_product_sid": trust_product_sid, "sid": sid or self.sid, } + self._context: Optional[TrustProductsChannelEndpointAssignmentContext] = None @property @@ -94,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 @@ -112,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 @@ -125,6 +161,7 @@ def __repr__(self) -> str: class TrustProductsChannelEndpointAssignmentContext(InstanceContext): + def __init__(self, version: Version, trust_product_sid: str, sid: str): """ Initialize the TrustProductsChannelEndpointAssignmentContext @@ -144,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 @@ -151,9 +202,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -163,9 +236,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsChannelEndpointAssignmentInstance 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) -> TrustProductsChannelEndpointAssignmentInstance: @@ -175,18 +272,45 @@ def fetch(self) -> TrustProductsChannelEndpointAssignmentInstance: :returns: The fetched TrustProductsChannelEndpointAssignmentInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], ) - return TrustProductsChannelEndpointAssignmentInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsChannelEndpointAssignmentInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TrustProductsChannelEndpointAssignmentInstance: """ @@ -195,18 +319,29 @@ async def fetch_async(self) -> TrustProductsChannelEndpointAssignmentInstance: :returns: The fetched TrustProductsChannelEndpointAssignmentInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TrustProductsChannelEndpointAssignmentInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], ) - return TrustProductsChannelEndpointAssignmentInstance( + 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: """ @@ -221,6 +356,7 @@ def __repr__(self) -> str: class TrustProductsChannelEndpointAssignmentPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> TrustProductsChannelEndpointAssignmentInstance: @@ -229,6 +365,7 @@ def get_instance( :param payload: Payload response from the API """ + return TrustProductsChannelEndpointAssignmentInstance( self._version, payload, @@ -245,6 +382,7 @@ def __repr__(self) -> str: class TrustProductsChannelEndpointAssignmentList(ListResource): + def __init__(self, version: Version, trust_product_sid: str): """ Initialize the TrustProductsChannelEndpointAssignmentList @@ -265,66 +403,142 @@ 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 + Internal helper for create operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "ChannelEndpointType": channel_endpoint_type, "ChannelEndpointSid": channel_endpoint_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, + 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( { "ChannelEndpointType": channel_endpoint_type, "ChannelEndpointSid": channel_endpoint_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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_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, @@ -391,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, @@ -414,6 +692,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( channel_endpoint_sid=channel_endpoint_sid, @@ -446,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( @@ -456,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, @@ -486,9 +828,15 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 TrustProductsChannelEndpointAssignmentPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_async( @@ -521,12 +869,102 @@ async def page_async( } ) + 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 + 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: """ @@ -539,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( @@ -555,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 306f9359b5..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 @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class TrustProductsEntityAssignmentsInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the Item Assignment resource. :ivar trust_product_sid: The unique string that we created to identify the TrustProduct resource. @@ -56,6 +55,7 @@ def __init__( "trust_product_sid": trust_product_sid, "sid": sid or self.sid, } + self._context: Optional[TrustProductsEntityAssignmentsContext] = None @property @@ -92,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 @@ -110,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 @@ -123,6 +159,7 @@ def __repr__(self) -> str: class TrustProductsEntityAssignmentsContext(InstanceContext): + def __init__(self, version: Version, trust_product_sid: str, sid: str): """ Initialize the TrustProductsEntityAssignmentsContext @@ -142,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 @@ -149,9 +200,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -161,9 +234,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the TrustProductsEntityAssignmentsInstance 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) -> TrustProductsEntityAssignmentsInstance: @@ -173,18 +270,45 @@ def fetch(self) -> TrustProductsEntityAssignmentsInstance: :returns: The fetched TrustProductsEntityAssignmentsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], ) - return TrustProductsEntityAssignmentsInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEntityAssignmentsInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TrustProductsEntityAssignmentsInstance: """ @@ -193,18 +317,29 @@ async def fetch_async(self) -> TrustProductsEntityAssignmentsInstance: :returns: The fetched TrustProductsEntityAssignmentsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TrustProductsEntityAssignmentsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], ) - return TrustProductsEntityAssignmentsInstance( + 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: """ @@ -219,6 +354,7 @@ def __repr__(self) -> str: class TrustProductsEntityAssignmentsPage(Page): + def get_instance( self, payload: Dict[str, Any] ) -> TrustProductsEntityAssignmentsInstance: @@ -227,6 +363,7 @@ def get_instance( :param payload: Payload response from the API """ + return TrustProductsEntityAssignmentsInstance( self._version, payload, @@ -243,6 +380,7 @@ def __repr__(self) -> str: class TrustProductsEntityAssignmentsList(ListResource): + def __init__(self, version: Version, trust_product_sid: str): """ Initialize the TrustProductsEntityAssignmentsList @@ -261,62 +399,119 @@ 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( { "ObjectSid": object_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "ObjectSid": object_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> Iterator[TrustProductsEntityAssignmentsInstance]: @@ -326,6 +521,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. + :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 @@ -336,12 +532,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(object_type=object_type, page_size=limits["page_size"]) return self._version.stream(page, limits["limit"]) async def stream_async( self, + object_type: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> AsyncIterator[TrustProductsEntityAssignmentsInstance]: @@ -351,6 +548,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. + :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 @@ -361,12 +559,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( + object_type=object_type, page_size=limits["page_size"] + ) 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, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[TrustProductsEntityAssignmentsInstance]: @@ -375,6 +632,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :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 @@ -384,8 +642,10 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( + object_type=object_type, limit=limit, page_size=page_size, ) @@ -393,6 +653,7 @@ def list( async def list_async( self, + object_type: Union[str, object] = values.unset, limit: Optional[int] = None, page_size: Optional[int] = None, ) -> List[TrustProductsEntityAssignmentsInstance]: @@ -401,6 +662,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. + :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 @@ -410,16 +672,75 @@ async def list_async( :returns: list that will contain up to limit results """ + return [ record async for record in await self.stream_async( + object_type=object_type, limit=limit, page_size=page_size, ) ] + 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, page_token: Union[str, object] = values.unset, page_number: Union[int, object] = values.unset, page_size: Union[int, object] = values.unset, @@ -428,6 +749,7 @@ def page( Retrieve a single page of TrustProductsEntityAssignmentsInstance records from the API. Request is executed immediately + :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 @@ -436,19 +758,27 @@ def page( """ data = values.of( { + "ObjectType": object_type, "PageToken": page_token, "Page": page_number, "PageSize": page_size, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 TrustProductsEntityAssignmentsPage( - self._version, response, self._solution + self._version, response, solution=self._solution ) async def page_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, @@ -457,6 +787,7 @@ async def page_async( Asynchronously retrieve a single page of TrustProductsEntityAssignmentsInstance records from the API. Request is executed immediately + :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 @@ -465,18 +796,103 @@ async def page_async( """ 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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + 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: """ @@ -489,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( @@ -505,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 f2d435c1cb..f27af2615f 100644 --- a/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py +++ b/twilio/rest/trusthub/v1/trust_products/trust_products_evaluations.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class TrustProductsEvaluationsInstance(InstanceResource): + class Status(object): COMPLIANT = "compliant" NONCOMPLIANT = "noncompliant" @@ -55,7 +56,7 @@ def __init__( self.status: Optional["TrustProductsEvaluationsInstance.Status"] = payload.get( "status" ) - self.results: Optional[List[object]] = payload.get("results") + self.results: Optional[List[Dict[str, object]]] = payload.get("results") self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -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 @@ -114,6 +134,7 @@ def __repr__(self) -> str: class TrustProductsEvaluationsContext(InstanceContext): + def __init__(self, version: Version, trust_product_sid: str, sid: str): """ Initialize the TrustProductsEvaluationsContext @@ -133,6 +154,22 @@ def __init__(self, version: Version, trust_product_sid: str, sid: str): **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) -> TrustProductsEvaluationsInstance: """ Fetch the TrustProductsEvaluationsInstance @@ -140,18 +177,45 @@ def fetch(self) -> TrustProductsEvaluationsInstance: :returns: The fetched TrustProductsEvaluationsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], ) - return TrustProductsEvaluationsInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the TrustProductsEvaluationsInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> TrustProductsEvaluationsInstance: """ @@ -160,18 +224,29 @@ async def fetch_async(self) -> TrustProductsEvaluationsInstance: :returns: The fetched TrustProductsEvaluationsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return TrustProductsEvaluationsInstance( + self._version, + payload, + trust_product_sid=self._solution["trust_product_sid"], + sid=self._solution["sid"], ) - return TrustProductsEvaluationsInstance( + 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: """ @@ -184,12 +259,14 @@ def __repr__(self) -> str: class TrustProductsEvaluationsPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TrustProductsEvaluationsInstance: """ Build an instance of TrustProductsEvaluationsInstance :param payload: Payload response from the API """ + return TrustProductsEvaluationsInstance( self._version, payload, @@ -206,6 +283,7 @@ def __repr__(self) -> str: class TrustProductsEvaluationsList(ListResource): + def __init__(self, version: Version, trust_product_sid: str): """ Initialize the TrustProductsEvaluationsList @@ -224,58 +302,114 @@ 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 - - :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 TrustProductsEvaluationsInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "PolicySid": policy_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "PolicySid": policy_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -326,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, @@ -345,6 +529,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -371,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( @@ -379,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, @@ -403,8 +639,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return TrustProductsEvaluationsPage(self._version, response, self._solution) + 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 TrustProductsEvaluationsPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -430,10 +674,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 ) - return TrustProductsEvaluationsPage(self._version, response, self._solution) + 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: """ @@ -445,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: """ @@ -457,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/verify/VerifyBase.py b/twilio/rest/verify/VerifyBase.py index 8977a50430..076f063147 100644 --- a/twilio/rest/verify/VerifyBase.py +++ b/twilio/rest/verify/VerifyBase.py @@ -17,6 +17,7 @@ class VerifyBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Verify Domain diff --git a/twilio/rest/verify/v2/__init__.py b/twilio/rest/verify/v2/__init__.py index c4f94aea30..01bee13b0d 100644 --- a/twilio/rest/verify/v2/__init__.py +++ b/twilio/rest/verify/v2/__init__.py @@ -26,6 +26,7 @@ class V2(Version): + def __init__(self, domain: Domain): """ Initialize the V2 version of Verify diff --git a/twilio/rest/verify/v2/form.py b/twilio/rest/verify/v2/form.py index 9b17da9e48..223f6b6d15 100644 --- a/twilio/rest/verify/v2/form.py +++ b/twilio/rest/verify/v2/form.py @@ -12,8 +12,9 @@ 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 @@ -21,6 +22,7 @@ class FormInstance(InstanceResource): + class FormTypes(object): FORM_PUSH = "form-push" @@ -47,6 +49,7 @@ def __init__( self._solution = { "form_type": form_type or self.form_type, } + self._context: Optional[FormContext] = None @property @@ -82,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 @@ -93,6 +114,7 @@ def __repr__(self) -> str: class FormContext(InstanceContext): + def __init__(self, version: Version, form_type: "FormInstance.FormTypes"): """ Initialize the FormContext @@ -108,6 +130,22 @@ def __init__(self, version: Version, form_type: "FormInstance.FormTypes"): } self._uri = "/Forms/{form_type}".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) -> FormInstance: """ Fetch the FormInstance @@ -115,17 +153,43 @@ def fetch(self) -> FormInstance: :returns: The fetched FormInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], ) - return FormInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FormInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FormInstance: """ @@ -134,17 +198,27 @@ async def fetch_async(self) -> FormInstance: :returns: The fetched FormInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return FormInstance( + self._version, + payload, + form_type=self._solution["form_type"], ) - return FormInstance( + 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: """ @@ -157,6 +231,7 @@ def __repr__(self) -> str: class FormList(ListResource): + def __init__(self, version: Version): """ Initialize the FormList diff --git a/twilio/rest/verify/v2/safelist.py b/twilio/rest/verify/v2/safelist.py index 45e5b220e1..9ea8069e48 100644 --- a/twilio/rest/verify/v2/safelist.py +++ b/twilio/rest/verify/v2/safelist.py @@ -12,9 +12,9 @@ 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 @@ -22,7 +22,6 @@ class SafelistInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the SafeList resource. :ivar phone_number: The phone number in SafeList. @@ -44,6 +43,7 @@ def __init__( self._solution = { "phone_number": phone_number or self.phone_number, } + self._context: Optional[SafelistContext] = None @property @@ -79,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 @@ -97,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 @@ -108,6 +144,7 @@ def __repr__(self) -> str: class SafelistContext(InstanceContext): + def __init__(self, version: Version, phone_number: str): """ Initialize the SafelistContext @@ -123,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 @@ -130,9 +181,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -142,9 +215,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SafelistInstance 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) -> SafelistInstance: @@ -154,17 +251,43 @@ def fetch(self) -> SafelistInstance: :returns: The fetched SafelistInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], ) - return SafelistInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SafelistInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SafelistInstance: """ @@ -173,17 +296,27 @@ async def fetch_async(self) -> SafelistInstance: :returns: The fetched SafelistInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SafelistInstance( + self._version, + payload, + phone_number=self._solution["phone_number"], ) - return SafelistInstance( + 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: """ @@ -196,6 +329,7 @@ def __repr__(self) -> str: class SafelistList(ListResource): + def __init__(self, version: Version): """ Initialize the SafelistList @@ -207,50 +341,100 @@ 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( { "PhoneNumber": phone_number, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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) -> 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( { "PhoneNumber": phone_number, } ) + 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, + 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 c9f3f4ea26..ed9b7747be 100644 --- a/twilio/rest/verify/v2/service/__init__.py +++ b/twilio/rest/verify/v2/service/__init__.py @@ -12,20 +12,24 @@ 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 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 @@ -33,11 +37,10 @@ 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 string that you assigned to describe the verification service. **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. @@ -45,10 +48,13 @@ class ServiceInstance(InstanceResource): :ivar dtmf_input_required: Whether to ask the user to press a number before delivering the verify code in a phone call. :ivar tts_name: The name of an alternative text-to-speech service to use in phone calls. Applies only to TTS languages. :ivar 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` - :ivar custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. Not available for all customers. + :ivar custom_code_enabled: Whether to allow sending verifications with a custom code instead of a randomly generated one. :ivar push: Configurations for the Push factors (channel) created under this Service. :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. :ivar url: The absolute URL of the resource. @@ -80,6 +86,11 @@ def __init__( self.push: Optional[Dict[str, object]] = payload.get("push") 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" + ) self.date_created: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_created") ) @@ -92,6 +103,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ServiceContext] = None @property @@ -127,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 @@ -145,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, @@ -164,11 +212,20 @@ def update( 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": """ Update the ServiceInstance - :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 30 characters long. **This value should not contain PII.** + :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`. @@ -176,7 +233,7 @@ def update( :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. Not available for all customers. + :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) @@ -185,6 +242,15 @@ def update( :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: The updated ServiceInstance """ @@ -206,6 +272,15 @@ def update( 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_async( @@ -227,11 +302,20 @@ async def update_async( 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": """ Asynchronous coroutine to update the ServiceInstance - :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 30 characters long. **This value should not contain PII.** + :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`. @@ -239,7 +323,7 @@ async def update_async( :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. Not available for all customers. + :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) @@ -248,6 +332,15 @@ async def update_async( :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: The updated ServiceInstance """ @@ -269,6 +362,195 @@ async def update_async( 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, + ) + + 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, ) @property @@ -278,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: """ @@ -292,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: """ @@ -331,6 +641,7 @@ def __repr__(self) -> str: class ServiceContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ServiceContext @@ -347,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 @@ -361,9 +690,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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: @@ -373,9 +724,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -385,17 +760,43 @@ def fetch(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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: """ @@ -404,19 +805,29 @@ async def fetch_async(self) -> ServiceInstance: :returns: The fetched ServiceInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ServiceInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ServiceInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, code_length: Union[int, object] = values.unset, @@ -435,42 +846,39 @@ def update( totp_code_length: Union[int, object] = values.unset, totp_skew: Union[int, object] = values.unset, default_template_sid: Union[str, object] = values.unset, - ) -> ServiceInstance: + 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: """ - Update the ServiceInstance - - :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 30 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. Not available for all customers. - :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. + Internal helper for update operation - :returns: The updated ServiceInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, "CodeLength": code_length, - "LookupEnabled": lookup_enabled, - "SkipSmsToLandlines": skip_sms_to_landlines, - "DtmfInputRequired": dtmf_input_required, + "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": psd2_enabled, - "DoNotShareWarningEnabled": do_not_share_warning_enabled, - "CustomCodeEnabled": custom_code_enabled, - "Push.IncludeDate": push_include_date, + "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, @@ -478,18 +886,30 @@ def update( "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({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - async def update_async( + 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, code_length: Union[int, object] = values.unset, @@ -508,11 +928,20 @@ async def update_async( 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: """ - 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 30 characters long. **This value should not contain PII.** + :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`. @@ -520,7 +949,7 @@ async def update_async( :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. Not available for all customers. + :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) @@ -529,44 +958,410 @@ async def update_async( :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: The updated ServiceInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "CodeLength": code_length, - "LookupEnabled": lookup_enabled, - "SkipSmsToLandlines": skip_sms_to_landlines, - "DtmfInputRequired": dtmf_input_required, - "TtsName": tts_name, - "Psd2Enabled": psd2_enabled, - "DoNotShareWarningEnabled": do_not_share_warning_enabled, - "CustomCodeEnabled": custom_code_enabled, - "Push.IncludeDate": 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, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return ServiceInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def access_tokens(self) -> AccessTokenList: - """ - Access the access_tokens - """ + 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( + { + "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({}) + + 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, + 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: + """ + Asynchronous coroutine to 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. + :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: The updated ServiceInstance + """ + 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"]) + + 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 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 = 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, @@ -574,6 +1369,18 @@ def access_tokens(self) -> AccessTokenList: ) 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: """ @@ -598,6 +1405,42 @@ def messaging_configurations(self) -> MessagingConfigurationList: ) 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: """ @@ -657,12 +1500,14 @@ def __repr__(self) -> str: 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: @@ -675,6 +1520,7 @@ def __repr__(self) -> str: class ServiceList(ListResource): + def __init__(self, version: Version): """ Initialize the ServiceList @@ -686,7 +1532,180 @@ def __init__(self, version: Version): self._uri = "/Services" - def create( + 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, @@ -705,11 +1724,20 @@ def create( totp_code_length: Union[int, object] = values.unset, totp_skew: Union[int, object] = values.unset, default_template_sid: Union[str, 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 30 characters long. **This value should not contain PII.** + 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`. @@ -717,7 +1745,7 @@ def create( :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. Not available for all customers. + :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) @@ -726,21 +1754,101 @@ def create( :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) - :returns: The created ServiceInstance + 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": lookup_enabled, - "SkipSmsToLandlines": skip_sms_to_landlines, - "DtmfInputRequired": dtmf_input_required, + "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": psd2_enabled, - "DoNotShareWarningEnabled": do_not_share_warning_enabled, - "CustomCodeEnabled": custom_code_enabled, - "Push.IncludeDate": push_include_date, + "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, @@ -748,16 +1856,28 @@ def create( "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"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ServiceInstance(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, @@ -778,11 +1898,20 @@ async def create_async( 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: """ Asynchronously create the ServiceInstance - :param friendly_name: A descriptive string that you create to describe the verification service. It can be up to 30 characters long. **This value should not contain PII.** + :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`. @@ -790,7 +1919,7 @@ async def create_async( :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. Not available for all customers. + :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) @@ -799,38 +1928,139 @@ async def create_async( :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 """ - data = values.of( - { - "FriendlyName": friendly_name, - "CodeLength": code_length, - "LookupEnabled": lookup_enabled, - "SkipSmsToLandlines": skip_sms_to_landlines, - "DtmfInputRequired": dtmf_input_required, - "TtsName": tts_name, - "Psd2Enabled": psd2_enabled, - "DoNotShareWarningEnabled": do_not_share_warning_enabled, - "CustomCodeEnabled": custom_code_enabled, - "Push.IncludeDate": 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, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + async def create_with_http_info_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, + ) -> ApiResponse: + """ + 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. + :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 = 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, @@ -882,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, @@ -901,6 +2181,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -927,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( @@ -935,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, @@ -959,7 +2291,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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( @@ -986,11 +2324,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 8c1bc46f8f..a5ecc856b6 100644 --- a/twilio/rest/verify/v2/service/access_token.py +++ b/twilio/rest/verify/v2/service/access_token.py @@ -12,10 +12,10 @@ 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 @@ -23,6 +23,7 @@ class AccessTokenInstance(InstanceResource): + class FactorTypes(object): PUSH = "push" @@ -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 @@ -114,6 +134,7 @@ def __repr__(self) -> str: class AccessTokenContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the AccessTokenContext @@ -133,6 +154,22 @@ def __init__(self, version: Version, service_sid: str, sid: str): **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) -> AccessTokenInstance: """ Fetch the AccessTokenInstance @@ -140,18 +177,45 @@ def fetch(self) -> AccessTokenInstance: :returns: The fetched AccessTokenInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return AccessTokenInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the AccessTokenInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> AccessTokenInstance: """ @@ -160,18 +224,29 @@ async def fetch_async(self) -> AccessTokenInstance: :returns: The fetched AccessTokenInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return AccessTokenInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return AccessTokenInstance( + 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: """ @@ -184,6 +259,7 @@ def __repr__(self) -> str: class AccessTokenList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the AccessTokenList @@ -200,6 +276,38 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/AccessTokens".format(**self._solution) + def _create( + self, + identity: str, + factor_type: "AccessTokenInstance.FactorTypes", + factor_friendly_name: Union[str, object] = values.unset, + ttl: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Identity": identity, + "FactorType": factor_type, + "FactorFriendlyName": factor_friendly_name, + "Ttl": ttl, + } + ) + 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, identity: str, @@ -217,6 +325,58 @@ def create( :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"] + ) + + 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, + ) -> ApiResponse: + """ + 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 = 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( { "Identity": identity, @@ -225,15 +385,14 @@ def create( "Ttl": ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return AccessTokenInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -253,24 +412,43 @@ async def create_async( :returns: The created AccessTokenInstance """ - data = values.of( - { - "Identity": identity, - "FactorType": factor_type, - "FactorFriendlyName": factor_friendly_name, - "Ttl": ttl, - } + payload, _, _ = await self._create_async( + identity=identity, + factor_type=factor_type, + factor_friendly_name=factor_friendly_name, + ttl=ttl, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return AccessTokenInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return AccessTokenInstance( + 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: """ 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 "".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 "" diff --git a/twilio/rest/verify/v2/service/entity/__init__.py b/twilio/rest/verify/v2/service/entity/__init__.py index 74629d9bb2..f7f506f57a 100644 --- a/twilio/rest/verify/v2/service/entity/__init__.py +++ b/twilio/rest/verify/v2/service/entity/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class EntityInstance(InstanceResource): - """ :ivar sid: A 34 character string that uniquely identifies this Entity. :ivar 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. @@ -65,6 +64,7 @@ def __init__( "service_sid": service_sid, "identity": identity or self.identity, } + self._context: Optional[EntityContext] = None @property @@ -101,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 @@ -119,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: """ @@ -151,6 +187,7 @@ def __repr__(self) -> str: class EntityContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, identity: str): """ Initialize the EntityContext @@ -174,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 @@ -181,9 +232,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -193,9 +266,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the EntityInstance 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) -> EntityInstance: @@ -205,18 +302,45 @@ def fetch(self) -> EntityInstance: :returns: The fetched EntityInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], ) - return EntityInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the EntityInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> EntityInstance: """ @@ -225,18 +349,29 @@ async def fetch_async(self) -> EntityInstance: :returns: The fetched EntityInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return EntityInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], ) - return EntityInstance( + 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: @@ -288,12 +423,14 @@ def __repr__(self) -> str: class EntityPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> EntityInstance: """ Build an instance of EntityInstance :param payload: Payload response from the API """ + return EntityInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -308,6 +445,7 @@ def __repr__(self) -> str: class EntityList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the EntityList @@ -324,54 +462,106 @@ 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 - - :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. + Internal helper for create operation - :returns: The created EntityInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Identity": identity, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "Identity": identity, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -422,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, @@ -441,6 +681,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -467,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( @@ -475,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, @@ -499,8 +791,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return EntityPage(self._version, response, self._solution) + 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 EntityPage(self._version, response, solution=self._solution) async def page_async( self, @@ -526,10 +824,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return EntityPage(self._version, response, self._solution) + 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: """ @@ -541,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: """ @@ -553,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 65aab902b1..9940cbf831 100644 --- a/twilio/rest/verify/v2/service/entity/challenge/__init__.py +++ b/twilio/rest/verify/v2/service/entity/challenge/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,6 +25,7 @@ class ChallengeInstance(InstanceResource): + class ChallengeReasons(object): NONE = "none" NOT_NEEDED = "not_needed" @@ -39,6 +40,7 @@ class ChallengeStatuses(object): class FactorTypes(object): PUSH = "push" TOTP = "totp" + PASSKEYS = "passkeys" class ListOrders(object): ASC = "asc" @@ -96,9 +98,9 @@ def __init__( self.status: Optional["ChallengeInstance.ChallengeStatuses"] = payload.get( "status" ) - self.responded_reason: Optional[ - "ChallengeInstance.ChallengeReasons" - ] = payload.get("responded_reason") + self.responded_reason: Optional["ChallengeInstance.ChallengeReasons"] = ( + 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") @@ -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: """ @@ -204,6 +261,7 @@ def __repr__(self) -> str: class ChallengeContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, identity: str, sid: str): """ Initialize the ChallengeContext @@ -229,6 +287,22 @@ def __init__(self, version: Version, service_sid: str, identity: str, sid: str): self._notifications: Optional[NotificationList] = None + 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) -> ChallengeInstance: """ Fetch the ChallengeInstance @@ -236,19 +310,47 @@ def fetch(self) -> ChallengeInstance: :returns: The fetched ChallengeInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], ) - return ChallengeInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ChallengeInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ChallengeInstance: """ @@ -257,46 +359,74 @@ async def fetch_async(self) -> ChallengeInstance: :returns: The fetched ChallengeInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ChallengeInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], ) - return ChallengeInstance( + 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( + def _update( self, auth_payload: Union[str, object] = values.unset, metadata: Union[object, object] = values.unset, - ) -> ChallengeInstance: + ) -> tuple: """ - Update the ChallengeInstance + Internal helper for update operation - :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: + tuple: (payload, status_code, headers) """ + data = values.of( { "AuthPayload": auth_payload, "Metadata": serialize.object(metadata), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -305,32 +435,75 @@ 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( { "AuthPayload": auth_payload, "Metadata": serialize.object(metadata), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -339,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: """ @@ -364,12 +562,14 @@ def __repr__(self) -> str: class ChallengePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ChallengeInstance: """ Build an instance of ChallengeInstance :param payload: Payload response from the API """ + return ChallengeInstance( self._version, payload, @@ -387,6 +587,7 @@ def __repr__(self) -> str: class ChallengeList(ListResource): + def __init__(self, version: Version, service_sid: str, identity: str): """ Initialize the ChallengeList @@ -407,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, @@ -415,19 +616,14 @@ 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 - - :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. + Internal helper for create operation - :returns: The created ChallengeInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FactorSid": factor_sid, @@ -440,13 +636,45 @@ def create( "AuthPayload": auth_payload, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -454,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, @@ -462,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. @@ -473,8 +701,40 @@ 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( { "FactorSid": factor_sid, @@ -487,13 +747,45 @@ async def create_async( "AuthPayload": auth_payload, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -501,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, @@ -573,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, @@ -598,6 +997,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( factor_sid=factor_sid, @@ -633,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( @@ -644,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, @@ -677,8 +1146,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ChallengePage(self._version, response, self._solution) + 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 ChallengePage(self._version, response, solution=self._solution) async def page_async( self, @@ -713,10 +1188,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ChallengePage(self._version, response, self._solution) + 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: """ @@ -728,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: """ @@ -740,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 a04fea65ed..4250597da6 100644 --- a/twilio/rest/verify/v2/service/entity/challenge/notification.py +++ b/twilio/rest/verify/v2/service/entity/challenge/notification.py @@ -12,10 +12,10 @@ 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 @@ -23,7 +23,6 @@ class NotificationInstance(InstanceResource): - """ :ivar sid: A 34 character string that uniquely identifies this Notification. :ivar account_sid: The unique SID identifier of the Account. @@ -75,6 +74,7 @@ def __repr__(self) -> str: class NotificationList(ListResource): + def __init__( self, version: Version, service_sid: str, identity: str, challenge_sid: str ): @@ -99,26 +99,38 @@ 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( { "Ttl": ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -127,28 +139,60 @@ 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( { "Ttl": ttl, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -157,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 b46a643717..823dd53f69 100644 --- a/twilio/rest/verify/v2/service/entity/factor.py +++ b/twilio/rest/verify/v2/service/entity/factor.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class FactorInstance(InstanceResource): + class FactorStatuses(object): UNVERIFIED = "unverified" VERIFIED = "verified" @@ -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 @@ -232,6 +349,7 @@ def __repr__(self) -> str: class FactorContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, identity: str, sid: str): """ Initialize the FactorContext @@ -253,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 @@ -260,9 +392,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -272,9 +426,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the FactorInstance 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) -> FactorInstance: @@ -284,19 +462,47 @@ def fetch(self) -> FactorInstance: :returns: The fetched FactorInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], ) - return FactorInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the FactorInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> FactorInstance: """ @@ -305,21 +511,33 @@ async def fetch_async(self) -> FactorInstance: :returns: The fetched FactorInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return FactorInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + identity=self._solution["identity"], + sid=self._solution["sid"], ) - return FactorInstance( + 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( + def _update( self, auth_payload: Union[str, object] = values.unset, friendly_name: Union[str, object] = values.unset, @@ -330,22 +548,14 @@ 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 - - :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`. + Internal helper for update operation - :returns: The updated FactorInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "AuthPayload": auth_payload, @@ -359,13 +569,54 @@ def update( "Config.NotificationPlatform": config_notification_platform, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -374,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, @@ -385,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. @@ -399,8 +650,47 @@ 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( { "AuthPayload": auth_payload, @@ -414,13 +704,54 @@ async def update_async( "Config.NotificationPlatform": config_notification_platform, } ) + 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, + 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, @@ -429,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 @@ -440,12 +818,14 @@ def __repr__(self) -> str: class FactorPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> FactorInstance: """ Build an instance of FactorInstance :param payload: Payload response from the API """ + return FactorInstance( self._version, payload, @@ -463,6 +843,7 @@ def __repr__(self) -> str: class FactorList(ListResource): + def __init__(self, version: Version, service_sid: str, identity: str): """ Initialize the FactorList @@ -533,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, @@ -552,6 +983,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -578,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( @@ -586,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, @@ -610,8 +1093,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return FactorPage(self._version, response, self._solution) + 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 FactorPage(self._version, response, solution=self._solution) async def page_async( self, @@ -637,10 +1126,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return FactorPage(self._version, response, self._solution) + 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: """ @@ -652,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: """ @@ -664,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 71c793cc65..79184c0e74 100644 --- a/twilio/rest/verify/v2/service/entity/new_factor.py +++ b/twilio/rest/verify/v2/service/entity/new_factor.py @@ -12,10 +12,10 @@ 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 @@ -23,6 +23,7 @@ class NewFactorInstance(InstanceResource): + class FactorStatuses(object): UNVERIFIED = "unverified" VERIFIED = "verified" @@ -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") ) @@ -102,6 +106,7 @@ def __repr__(self) -> str: class NewFactorList(ListResource): + def __init__(self, version: Version, service_sid: str, identity: str): """ Initialize the NewFactorList @@ -122,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", @@ -140,27 +145,14 @@ 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 + Internal helper for create operation - :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 + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, @@ -179,13 +171,71 @@ def create( "Metadata": serialize.object(metadata), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -193,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", @@ -211,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: @@ -230,8 +280,58 @@ 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( { "FriendlyName": friendly_name, @@ -250,13 +350,71 @@ async def create_async( "Metadata": serialize.object(metadata), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -264,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 9d6092d543..43920cc5b9 100644 --- a/twilio/rest/verify/v2/service/messaging_configuration.py +++ b/twilio/rest/verify/v2/service/messaging_configuration.py @@ -12,10 +12,10 @@ 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 @@ -24,12 +24,11 @@ class MessagingConfigurationInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Service resource. :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) that the resource is associated with. :ivar 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`. - :ivar messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/services/api) to be used to send SMS to the country of this configuration. + :ivar 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. :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 url: The URL of this resource. @@ -60,6 +59,7 @@ def __init__( "service_sid": service_sid, "country": country or self.country, } + self._context: Optional[MessagingConfigurationContext] = None @property @@ -96,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 @@ -114,11 +132,29 @@ 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 - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/services/api) to be used to send SMS to the country of this configuration. + :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 """ @@ -132,7 +168,7 @@ async def update_async( """ Asynchronous coroutine to update the MessagingConfigurationInstance - :param messaging_service_sid: The SID of the [Messaging Service](https://www.twilio.com/docs/sms/services/api) to be used to send SMS to the country of this configuration. + :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 """ @@ -140,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 @@ -151,6 +213,7 @@ def __repr__(self) -> str: class MessagingConfigurationContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, country: str): """ Initialize the MessagingConfigurationContext @@ -170,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 @@ -177,9 +254,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -189,9 +288,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the MessagingConfigurationInstance 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) -> MessagingConfigurationInstance: @@ -201,18 +324,45 @@ def fetch(self) -> MessagingConfigurationInstance: :returns: The fetched MessagingConfigurationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return MessagingConfigurationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + country=self._solution["country"], ) - return MessagingConfigurationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the MessagingConfigurationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> MessagingConfigurationInstance: """ @@ -221,12 +371,7 @@ async def fetch_async(self) -> MessagingConfigurationInstance: :returns: The fetched MessagingConfigurationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return MessagingConfigurationInstance( self._version, payload, @@ -234,26 +379,54 @@ 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/sms/services/api) 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( { "MessagingServiceSid": messaging_service_sid, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -261,28 +434,61 @@ 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/sms/services/api) to be used to send SMS to the country of this configuration. + :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( { "MessagingServiceSid": messaging_service_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, + 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, @@ -290,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 @@ -301,12 +528,14 @@ def __repr__(self) -> str: class MessagingConfigurationPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> MessagingConfigurationInstance: """ Build an instance of MessagingConfigurationInstance :param payload: Payload response from the API """ + return MessagingConfigurationInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -321,6 +550,7 @@ def __repr__(self) -> str: class MessagingConfigurationList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the MessagingConfigurationList @@ -339,6 +569,30 @@ def __init__(self, version: Version, service_sid: str): **self._solution ) + def _create(self, country: str, messaging_service_sid: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Country": country, + "MessagingServiceSid": messaging_service_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, country: str, messaging_service_sid: str ) -> MessagingConfigurationInstance: @@ -346,25 +600,58 @@ def create( 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/sms/services/api) to be used to send SMS to the country of this configuration. + :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"] + ) + + def create_with_http_info( + self, country: str, messaging_service_sid: str + ) -> ApiResponse: + """ + 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 = 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( { "Country": country, "MessagingServiceSid": messaging_service_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return MessagingConfigurationInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -374,26 +661,35 @@ async def create_async( 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/sms/services/api) to be used to send SMS to the country of this configuration. + :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 """ - data = values.of( - { - "Country": country, - "MessagingServiceSid": messaging_service_sid, - } + payload, _, _ = await self._create_async( + country=country, messaging_service_sid=messaging_service_sid ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return MessagingConfigurationInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return MessagingConfigurationInstance( + 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, @@ -445,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, @@ -464,6 +810,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -490,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( @@ -498,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, @@ -522,8 +920,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return MessagingConfigurationPage(self._version, response, self._solution) + 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 MessagingConfigurationPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -549,10 +955,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 MessagingConfigurationPage(self._version, response, self._solution) + return ApiResponse(data=page, status_code=status_code, headers=response_headers) def get_page(self, target_url: str) -> MessagingConfigurationPage: """ @@ -564,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: """ @@ -576,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 "".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 "".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 "" 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 "".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 "" 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 "".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 "" diff --git a/twilio/rest/verify/v2/service/rate_limit/__init__.py b/twilio/rest/verify/v2/service/rate_limit/__init__.py index f411c57e65..e01a326d9e 100644 --- a/twilio/rest/verify/v2/service/rate_limit/__init__.py +++ b/twilio/rest/verify/v2/service/rate_limit/__init__.py @@ -12,10 +12,10 @@ 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 @@ -25,7 +25,6 @@ class RateLimitInstance(InstanceResource): - """ :ivar sid: A 34 character string that uniquely identifies this Rate Limit. :ivar service_sid: The SID of the [Service](https://www.twilio.com/docs/verify/api/service) the resource is associated with. @@ -65,6 +64,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[RateLimitContext] = None @property @@ -101,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 @@ -119,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": @@ -147,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: """ @@ -165,6 +229,7 @@ def __repr__(self) -> str: class RateLimitContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the RateLimitContext @@ -184,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 @@ -191,9 +270,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -203,9 +304,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RateLimitInstance 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) -> RateLimitInstance: @@ -215,18 +340,45 @@ def fetch(self) -> RateLimitInstance: :returns: The fetched RateLimitInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RateLimitInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return RateLimitInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RateLimitInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RateLimitInstance: """ @@ -235,12 +387,7 @@ async def fetch_async(self) -> RateLimitInstance: :returns: The fetched RateLimitInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return RateLimitInstance( self._version, payload, @@ -248,28 +395,56 @@ 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( { "Description": description, } ) + 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, + 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, @@ -277,28 +452,61 @@ 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( { "Description": description, } ) + 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, + 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, @@ -306,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: """ @@ -330,12 +559,14 @@ def __repr__(self) -> str: class RateLimitPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RateLimitInstance: """ Build an instance of RateLimitInstance :param payload: Payload response from the API """ + return RateLimitInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -350,6 +581,7 @@ def __repr__(self) -> str: class RateLimitList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the RateLimitList @@ -366,6 +598,32 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/RateLimits".format(**self._solution) + def _create( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "Description": description, + } + ) + 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, unique_name: str, description: Union[str, object] = values.unset ) -> RateLimitInstance: @@ -377,21 +635,54 @@ def create( :returns: The created RateLimitInstance """ + payload, _, _ = self._create(unique_name=unique_name, description=description) + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] + ) + + def create_with_http_info( + self, unique_name: str, description: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "UniqueName": unique_name, "Description": description, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RateLimitInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -405,22 +696,31 @@ async def create_async( :returns: The created RateLimitInstance """ - data = values.of( - { - "UniqueName": unique_name, - "Description": description, - } + payload, _, _ = await self._create_async( + unique_name=unique_name, description=description ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return RateLimitInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return RateLimitInstance( + 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, @@ -472,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, @@ -491,6 +841,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -517,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( @@ -525,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, @@ -549,8 +951,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RateLimitPage(self._version, response, self._solution) + 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 RateLimitPage(self._version, response, solution=self._solution) async def page_async( self, @@ -576,10 +984,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RateLimitPage(self._version, response, self._solution) + 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: """ @@ -591,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: """ @@ -603,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 a97b1e0171..9b47a70c3c 100644 --- a/twilio/rest/verify/v2/service/rate_limit/bucket.py +++ b/twilio/rest/verify/v2/service/rate_limit/bucket.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class BucketInstance(InstanceResource): - """ :ivar sid: A 34 character string that uniquely identifies this Bucket. :ivar rate_limit_sid: The Twilio-provided string that uniquely identifies the Rate Limit resource. @@ -66,6 +65,7 @@ def __init__( "rate_limit_sid": rate_limit_sid, "sid": sid or self.sid, } + self._context: Optional[BucketContext] = None @property @@ -103,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 @@ -121,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, @@ -157,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 @@ -168,6 +240,7 @@ def __repr__(self) -> str: class BucketContext(InstanceContext): + def __init__( self, version: Version, service_sid: str, rate_limit_sid: str, sid: str ): @@ -193,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 @@ -200,9 +287,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -212,9 +321,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -224,19 +357,47 @@ def fetch(self) -> BucketInstance: :returns: The fetched BucketInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], ) - return BucketInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> BucketInstance: """ @@ -245,46 +406,74 @@ async def fetch_async(self) -> BucketInstance: :returns: The fetched BucketInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return BucketInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + rate_limit_sid=self._solution["rate_limit_sid"], + sid=self._solution["sid"], ) - return BucketInstance( + 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( + 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( { "Max": max, "Interval": interval, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -293,32 +482,71 @@ 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( { "Max": max, "Interval": interval, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -327,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 @@ -338,12 +591,14 @@ def __repr__(self) -> str: class BucketPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> BucketInstance: """ Build an instance of BucketInstance :param payload: Payload response from the API """ + return BucketInstance( self._version, payload, @@ -361,6 +616,7 @@ def __repr__(self) -> str: class BucketList(ListResource): + def __init__(self, version: Version, service_sid: str, rate_limit_sid: str): """ Initialize the BucketList @@ -383,28 +639,40 @@ 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( { "Max": max, "Interval": interval, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -412,28 +680,58 @@ 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( { "Max": max, "Interval": interval, } ) + 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, + 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, @@ -441,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, @@ -491,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, @@ -510,6 +878,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -536,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( @@ -544,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, @@ -568,8 +988,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return BucketPage(self._version, response, self._solution) + 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 BucketPage(self._version, response, solution=self._solution) async def page_async( self, @@ -595,10 +1021,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return BucketPage(self._version, response, self._solution) + 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: """ @@ -610,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: """ @@ -622,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 2a72f7e110..88ae5cb750 100644 --- a/twilio/rest/verify/v2/service/verification.py +++ b/twilio/rest/verify/v2/service/verification.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,6 +23,7 @@ class VerificationInstance(InstanceResource): + class Channel(object): SMS = "sms" CALL = "call" @@ -30,6 +31,10 @@ class Channel(object): WHATSAPP = "whatsapp" SNA = "sna" + class RiskCheck(object): + ENABLE = "enable" + DISABLE = "disable" + class Status(object): CANCELED = "canceled" APPROVED = "approved" @@ -40,7 +45,7 @@ class Status(object): :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Verification resource. :ivar to: The phone number or [email](https://www.twilio.com/docs/verify/email) being verified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :ivar channel: - :ivar status: The status of the verification. One of: `pending`, `approved`, or `canceled` + :ivar status: The status of the verification. Can be: `pending`, `approved`, `canceled`, `max_attempts_reached`, `deleted`, `failed` or `expired`. :ivar valid: Use \"status\" instead. Legacy property indicating whether the verification was successful. :ivar lookup: Information about the phone number being verified. :ivar amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. @@ -71,7 +76,7 @@ def __init__( self.lookup: Optional[Dict[str, object]] = payload.get("lookup") self.amount: Optional[str] = payload.get("amount") self.payee: Optional[str] = payload.get("payee") - self.send_code_attempts: Optional[List[object]] = payload.get( + self.send_code_attempts: Optional[List[Dict[str, object]]] = payload.get( "send_code_attempts" ) self.date_created: Optional[datetime] = deserialize.iso8601_datetime( @@ -87,6 +92,7 @@ def __init__( "service_sid": service_sid, "sid": sid or self.sid, } + self._context: Optional[VerificationContext] = None @property @@ -123,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 @@ -149,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 @@ -160,6 +212,7 @@ def __repr__(self) -> str: class VerificationContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the VerificationContext @@ -179,6 +232,22 @@ def __init__(self, version: Version, service_sid: str, sid: str): **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) -> VerificationInstance: """ Fetch the VerificationInstance @@ -186,18 +255,45 @@ def fetch(self) -> VerificationInstance: :returns: The fetched VerificationInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return VerificationInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return VerificationInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VerificationInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> VerificationInstance: """ @@ -206,12 +302,7 @@ async def fetch_async(self) -> VerificationInstance: :returns: The fetched VerificationInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + payload, _, _ = await self._fetch_async() return VerificationInstance( self._version, payload, @@ -219,26 +310,54 @@ 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( { "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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, @@ -246,28 +365,59 @@ 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( { "Status": status, } ) + 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, + 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, @@ -275,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 @@ -286,6 +455,7 @@ def __repr__(self) -> str: class VerificationList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the VerificationList @@ -302,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, @@ -319,28 +489,17 @@ def create( template_sid: Union[str, object] = values.unset, template_custom_substitutions: Union[str, object] = values.unset, device_ip: Union[str, object] = values.unset, - ) -> VerificationInstance: + enable_sna_client_token: Union[bool, object] = values.unset, + risk_check: Union["VerificationInstance.RiskCheck", object] = values.unset, + tags: Union[str, object] = values.unset, + ) -> tuple: """ - 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. - :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. + Internal helper for create operation - :returns: The created VerificationInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "To": to, @@ -358,20 +517,93 @@ def create( "TemplateSid": template_sid, "TemplateCustomSubstitutions": template_custom_substitutions, "DeviceIp": device_ip, + "EnableSnaClientToken": serialize.boolean_to_string( + enable_sna_client_token + ), + "RiskCheck": risk_check, + "Tags": tags, } ) + 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, + 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, @@ -388,14 +620,17 @@ async def create_async( template_sid: Union[str, object] = values.unset, template_custom_substitutions: Union[str, object] = values.unset, device_ip: Union[str, object] = values.unset, - ) -> VerificationInstance: + 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 + 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. @@ -407,9 +642,65 @@ async def create_async( :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 = 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( { "To": to, @@ -427,19 +718,162 @@ async def create_async( "TemplateSid": template_sid, "TemplateCustomSubstitutions": template_custom_substitutions, "DeviceIp": device_ip, + "EnableSnaClientToken": serialize.boolean_to_string( + enable_sna_client_token + ), + "RiskCheck": risk_check, + "Tags": tags, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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 05a8399f87..b80c8d6d46 100644 --- a/twilio/rest/verify/v2/service/verification_check.py +++ b/twilio/rest/verify/v2/service/verification_check.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,6 +23,7 @@ class VerificationCheckInstance(InstanceResource): + class Channel(object): SMS = "sms" CALL = "call" @@ -36,7 +37,7 @@ class Channel(object): :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the VerificationCheck resource. :ivar to: The phone number or [email](https://www.twilio.com/docs/verify/email) being verified. Phone numbers must be in [E.164 format](https://www.twilio.com/docs/glossary/what-e164). :ivar channel: - :ivar status: The status of the verification. Can be: `pending`, `approved`, or `canceled`. + :ivar status: The status of the verification. Can be: `pending`, `approved`, `canceled`, `max_attempts_reached`, `deleted`, `failed` or `expired`. :ivar valid: Use \"status\" instead. Legacy property indicating whether the verification was successful. :ivar amount: The amount of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. :ivar payee: The payee of the associated PSD2 compliant transaction. Requires the PSD2 Service flag enabled. @@ -65,7 +66,7 @@ def __init__(self, version: Version, payload: Dict[str, Any], service_sid: str): self.date_updated: Optional[datetime] = deserialize.iso8601_datetime( payload.get("date_updated") ) - self.sna_attempts_error_codes: Optional[List[object]] = payload.get( + self.sna_attempts_error_codes: Optional[List[Dict[str, object]]] = payload.get( "sna_attempts_error_codes" ) @@ -84,6 +85,7 @@ def __repr__(self) -> str: class VerificationCheckList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the VerificationCheckList @@ -100,6 +102,42 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/VerificationCheck".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Code": code, + "To": to, + "VerificationSid": verification_sid, + "Amount": amount, + "Payee": payee, + "SnaClientToken": sna_client_token, + } + ) + 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, code: Union[str, object] = values.unset, @@ -107,6 +145,7 @@ def create( 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 @@ -116,9 +155,72 @@ def create( :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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "Code": code, @@ -126,17 +228,17 @@ def create( "VerificationSid": verification_sid, "Amount": amount, "Payee": payee, + "SnaClientToken": sna_client_token, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return VerificationCheckInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -146,6 +248,7 @@ async def create_async( 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 @@ -155,28 +258,55 @@ async def create_async( :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 """ - data = values.of( - { - "Code": code, - "To": to, - "VerificationSid": verification_sid, - "Amount": amount, - "Payee": payee, - } + payload, _, _ = await self._create_async( + code=code, + to=to, + verification_sid=verification_sid, + amount=amount, + payee=payee, + sna_client_token=sna_client_token, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return VerificationCheckInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return VerificationCheckInstance( + 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: """ diff --git a/twilio/rest/verify/v2/service/webhook.py b/twilio/rest/verify/v2/service/webhook.py index c7924db4bf..2e59c8c4bb 100644 --- a/twilio/rest/verify/v2/service/webhook.py +++ b/twilio/rest/verify/v2/service/webhook.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class WebhookInstance(InstanceResource): + class Methods(object): GET = "GET" POST = "POST" @@ -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: @@ -202,6 +294,7 @@ def __repr__(self) -> str: class WebhookContext(InstanceContext): + def __init__(self, version: Version, service_sid: str, sid: str): """ Initialize the WebhookContext @@ -219,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 @@ -226,9 +333,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -238,9 +367,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the WebhookInstance 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) -> WebhookInstance: @@ -250,18 +403,45 @@ def fetch(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the WebhookInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> WebhookInstance: """ @@ -270,54 +450,90 @@ async def fetch_async(self) -> WebhookInstance: :returns: The fetched WebhookInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return WebhookInstance( + self._version, + payload, + service_sid=self._solution["service_sid"], + sid=self._solution["sid"], ) - return WebhookInstance( + 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( + 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 + Internal helper for update 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 updated WebhookInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, "EventTypes": serialize.map(event_types, lambda e: e), "WebhookUrl": webhook_url, "Status": status, - "Version": version, + "Version": resource_version, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -325,41 +541,100 @@ 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( { "FriendlyName": friendly_name, "EventTypes": serialize.map(event_types, lambda e: e), "WebhookUrl": webhook_url, "Status": status, - "Version": version, + "Version": resource_version, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -367,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 @@ -378,12 +687,14 @@ def __repr__(self) -> str: class WebhookPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> WebhookInstance: """ Build an instance of WebhookInstance :param payload: Payload response from the API """ + return WebhookInstance( self._version, payload, service_sid=self._solution["service_sid"] ) @@ -398,6 +709,7 @@ def __repr__(self) -> str: class WebhookList(ListResource): + def __init__(self, version: Version, service_sid: str): """ Initialize the WebhookList @@ -414,13 +726,47 @@ def __init__(self, version: Version, service_sid: str): } self._uri = "/Services/{service_sid}/Webhooks".format(**self._solution) + 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, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "EventTypes": serialize.map(event_types, lambda e: e), + "WebhookUrl": webhook_url, + "Status": status, + "Version": resource_version, + } + ) + 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, event_types: List[str], webhook_url: str, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, ) -> WebhookInstance: """ Create the WebhookInstance @@ -429,28 +775,84 @@ def create( :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 """ + 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"] + ) + + def create_with_http_info( + 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: + """ + 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 = 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( { "FriendlyName": friendly_name, "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"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return WebhookInstance( - self._version, payload, service_sid=self._solution["service_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( @@ -459,7 +861,7 @@ async def create_async( event_types: List[str], webhook_url: str, status: Union["WebhookInstance.Status", object] = values.unset, - version: Union["WebhookInstance.Version", object] = values.unset, + resource_version: Union["WebhookInstance.Version", object] = values.unset, ) -> WebhookInstance: """ Asynchronously create the WebhookInstance @@ -468,29 +870,51 @@ async def create_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 created WebhookInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "EventTypes": serialize.map(event_types, lambda e: e), - "WebhookUrl": webhook_url, - "Status": status, - "Version": version, - } + payload, _, _ = await self._create_async( + friendly_name=friendly_name, + event_types=event_types, + webhook_url=webhook_url, + status=status, + resource_version=resource_version, ) - - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + return WebhookInstance( + self._version, payload, service_sid=self._solution["service_sid"] ) - return WebhookInstance( + 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, @@ -542,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, @@ -561,6 +1035,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -587,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( @@ -595,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, @@ -619,8 +1145,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return WebhookPage(self._version, response, self._solution) + 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 WebhookPage(self._version, response, solution=self._solution) async def page_async( self, @@ -646,10 +1178,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return WebhookPage(self._version, response, self._solution) + 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: """ @@ -661,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: """ @@ -673,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 c644746fc5..4dfecf8f57 100644 --- a/twilio/rest/verify/v2/template.py +++ b/twilio/rest/verify/v2/template.py @@ -12,9 +12,9 @@ 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 @@ -23,12 +23,11 @@ class TemplateInstance(InstanceResource): - """ :ivar sid: A 34 character string that uniquely identifies a Verification Template. :ivar account_sid: The unique SID identifier of the Account. - :ivar friendly_name: A descriptive string that you create to describe a Template. - :ivar channels: A list of channels that support the Template. Can include: sms, voice + :ivar friendly_name: A descriptive string that you create to describe a Template. It can be up to 32 characters long. + :ivar channels: A list of channels that support the Template. Can include: sms, voice. :ivar translations: An object that contains the different translations of the template. Every translation is identified by the language short name and contains its respective information as the approval status, text and created/modified date. """ @@ -52,12 +51,14 @@ def __repr__(self) -> str: class TemplatePage(Page): + def get_instance(self, payload: Dict[str, Any]) -> TemplateInstance: """ Build an instance of TemplateInstance :param payload: Payload response from the API """ + return TemplateInstance(self._version, payload) def __repr__(self) -> str: @@ -70,6 +71,7 @@ def __repr__(self) -> str: class TemplateList(ListResource): + def __init__(self, version: Version): """ Initialize the TemplateList @@ -93,7 +95,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str friendly_name: String filter used to query templates with a given friendly name + :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 @@ -120,7 +122,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str friendly_name: String filter used to query templates with a given friendly name + :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 @@ -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, @@ -148,7 +206,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str friendly_name: String filter used to query templates with a given friendly name + :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 @@ -158,6 +216,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( friendly_name=friendly_name, @@ -177,7 +236,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str friendly_name: String filter used to query templates with a given friendly name + :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 @@ -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, @@ -207,7 +323,7 @@ def page( Retrieve a single page of TemplateInstance records from the API. Request is executed immediately - :param friendly_name: String filter used to query templates with a given friendly name + :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 @@ -223,7 +339,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 TemplatePage(self._version, response) async def page_async( @@ -237,7 +359,7 @@ async def page_async( Asynchronously retrieve a single page of TemplateInstance records from the API. Request is executed immediately - :param friendly_name: String filter used to query templates with a given friendly name + :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 @@ -253,11 +375,91 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 1e7f827d27..4704ee828a 100644 --- a/twilio/rest/verify/v2/verification_attempt.py +++ b/twilio/rest/verify/v2/verification_attempt.py @@ -12,10 +12,10 @@ 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 @@ -24,11 +24,13 @@ class VerificationAttemptInstance(InstanceResource): + class Channels(object): SMS = "sms" CALL = "call" EMAIL = "email" WHATSAPP = "whatsapp" + RBM = "rbm" class ConversionStatus(object): CONVERTED = "converted" @@ -43,7 +45,7 @@ class ConversionStatus(object): :ivar date_updated: The date that this Attempt was updated, given in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. :ivar conversion_status: :ivar channel: - :ivar price: An object containing the charge for this verification attempt related to the channel costs and the currency used. The costs related to the succeeded verifications are not included. May not be immediately available. More information on pricing is available [here](https://www.twilio.com/verify/pricing). + :ivar price: An object containing the charge for this verification attempt related to the channel costs and the currency used. The costs related to the succeeded verifications are not included. May not be immediately available. More information on pricing is available [here](https://www.twilio.com/en-us/verify/pricing). :ivar channel_data: An object containing the channel specific information for an attempt. :ivar url: """ @@ -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 @@ -122,6 +143,7 @@ def __repr__(self) -> str: class VerificationAttemptContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the VerificationAttemptContext @@ -137,6 +159,22 @@ def __init__(self, version: Version, sid: str): } self._uri = "/Attempts/{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) -> VerificationAttemptInstance: """ Fetch the VerificationAttemptInstance @@ -144,17 +182,43 @@ def fetch(self) -> VerificationAttemptInstance: :returns: The fetched VerificationAttemptInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return VerificationAttemptInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the VerificationAttemptInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> VerificationAttemptInstance: """ @@ -163,17 +227,27 @@ async def fetch_async(self) -> VerificationAttemptInstance: :returns: The fetched VerificationAttemptInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return VerificationAttemptInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return VerificationAttemptInstance( + 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: """ @@ -186,12 +260,14 @@ def __repr__(self) -> str: class VerificationAttemptPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> VerificationAttemptInstance: """ Build an instance of VerificationAttemptInstance :param payload: Payload response from the API """ + return VerificationAttemptInstance(self._version, payload) def __repr__(self) -> str: @@ -204,6 +280,7 @@ def __repr__(self) -> str: class VerificationAttemptList(ListResource): + def __init__(self, version: Version): """ Initialize the VerificationAttemptList @@ -236,11 +313,11 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param datetime date_created_after: Datetime filter used to query Verification Attempts created after this datetime. Given as GMT in RFC 2822 format. - :param datetime date_created_before: Datetime filter used to query Verification Attempts created before this datetime. Given as GMT in RFC 2822 format. + :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. 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. @@ -289,11 +366,11 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param datetime date_created_after: Datetime filter used to query Verification Attempts created after this datetime. Given as GMT in RFC 2822 format. - :param datetime date_created_before: Datetime filter used to query Verification Attempts created before this datetime. Given as GMT in RFC 2822 format. + :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. 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. @@ -321,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, @@ -341,11 +522,11 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param datetime date_created_after: Datetime filter used to query Verification Attempts created after this datetime. Given as GMT in RFC 2822 format. - :param datetime date_created_before: Datetime filter used to query Verification Attempts created before this datetime. Given as GMT in RFC 2822 format. + :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. 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. @@ -358,6 +539,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( date_created_after=date_created_after, @@ -393,11 +575,11 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param datetime date_created_after: Datetime filter used to query Verification Attempts created after this datetime. Given as GMT in RFC 2822 format. - :param datetime date_created_before: Datetime filter used to query Verification Attempts created before this datetime. Given as GMT in RFC 2822 format. + :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. 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. @@ -410,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( @@ -426,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, @@ -446,11 +731,11 @@ def page( Retrieve a single page of VerificationAttemptInstance records from the API. Request is executed immediately - :param date_created_after: Datetime filter used to query Verification Attempts created after this datetime. Given as GMT in RFC 2822 format. - :param date_created_before: Datetime filter used to query Verification Attempts created before this datetime. Given as GMT in RFC 2822 format. + :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. 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. @@ -476,7 +761,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 VerificationAttemptPage(self._version, response) async def page_async( @@ -499,11 +790,11 @@ async def page_async( Asynchronously retrieve a single page of VerificationAttemptInstance records from the API. Request is executed immediately - :param date_created_after: Datetime filter used to query Verification Attempts created after this datetime. Given as GMT in RFC 2822 format. - :param date_created_before: Datetime filter used to query Verification Attempts created before this datetime. Given as GMT in RFC 2822 format. + :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. 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. @@ -529,11 +820,137 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 d516143708..0f226478b5 100644 --- a/twilio/rest/verify/v2/verification_attempts_summary.py +++ b/twilio/rest/verify/v2/verification_attempts_summary.py @@ -12,10 +12,10 @@ 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_context import InstanceContext from twilio.base.instance_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -23,11 +23,13 @@ class VerificationAttemptsSummaryInstance(InstanceResource): + class Channels(object): SMS = "sms" 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") @@ -85,10 +87,10 @@ def fetch( 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 RFC 2822 format. - :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in RFC 2822 format. + :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` and `CALL` + :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 @@ -117,10 +119,10 @@ async def fetch_async( 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 RFC 2822 format. - :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in RFC 2822 format. + :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` and `CALL` + :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 @@ -145,6 +211,7 @@ def __repr__(self) -> str: class VerificationAttemptsSummaryContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the VerificationAttemptsSummaryContext @@ -155,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, @@ -165,21 +232,15 @@ def fetch( "VerificationAttemptsSummaryInstance.Channels", object ] = values.unset, destination_prefix: Union[str, object] = values.unset, - ) -> VerificationAttemptsSummaryInstance: + ) -> tuple: """ - 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 RFC 2822 format. - :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in RFC 2822 format. - :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` and `CALL` - :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. + Internal helper for fetch operation - :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), @@ -190,14 +251,51 @@ def fetch( } ) - payload = self._version.fetch(method="GET", uri=self._uri, params=data) + 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, + 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, @@ -207,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 RFC 2822 format. - :param date_created_before: Datetime filter used to consider only Verification Attempts created before this datetime on the summary aggregation. Given as GMT in RFC 2822 format. + :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` and `CALL` + :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) - data = values.of( + 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 + + Returns: + tuple: (payload, status_code, headers) + """ + + params = values.of( { "VerifyServiceSid": verify_service_sid, "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), @@ -232,15 +361,87 @@ async def fetch_async( } ) - payload = await self._version.fetch_async( - method="GET", uri=self._uri, params=data + 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, + 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 @@ -252,6 +453,7 @@ def __repr__(self) -> str: class VerificationAttemptsSummaryList(ListResource): + def __init__(self, version: Version): """ Initialize the VerificationAttemptsSummaryList diff --git a/twilio/rest/video/VideoBase.py b/twilio/rest/video/VideoBase.py index 2a25345662..0d2cf7e364 100644 --- a/twilio/rest/video/VideoBase.py +++ b/twilio/rest/video/VideoBase.py @@ -17,6 +17,7 @@ class VideoBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Video Domain diff --git a/twilio/rest/video/v1/__init__.py b/twilio/rest/video/v1/__init__.py index 9cd9fcf352..0667596a3f 100644 --- a/twilio/rest/video/v1/__init__.py +++ b/twilio/rest/video/v1/__init__.py @@ -24,6 +24,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Video diff --git a/twilio/rest/video/v1/composition.py b/twilio/rest/video/v1/composition.py index 2fead14204..47bb8a9641 100644 --- a/twilio/rest/video/v1/composition.py +++ b/twilio/rest/video/v1/composition.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class CompositionInstance(InstanceResource): + class Format(object): MP4 = "mp4" WEBM = "webm" @@ -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 @@ -165,6 +203,7 @@ def __repr__(self) -> str: class CompositionContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CompositionContext @@ -180,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 @@ -187,9 +240,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -199,9 +274,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionInstance 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) -> CompositionInstance: @@ -211,17 +310,43 @@ def fetch(self) -> CompositionInstance: :returns: The fetched CompositionInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CompositionInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CompositionInstance: """ @@ -230,17 +355,27 @@ async def fetch_async(self) -> CompositionInstance: :returns: The fetched CompositionInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CompositionInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CompositionInstance( + 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: """ @@ -253,12 +388,14 @@ def __repr__(self) -> str: class CompositionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CompositionInstance: """ Build an instance of CompositionInstance :param payload: Payload response from the API """ + return CompositionInstance(self._version, payload) def __repr__(self) -> str: @@ -271,6 +408,7 @@ def __repr__(self) -> str: class CompositionList(ListResource): + def __init__(self, version: Version): """ Initialize the CompositionList @@ -282,6 +420,50 @@ def __init__(self, version: Version): self._uri = "/Compositions" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "RoomSid": room_sid, + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + 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, room_sid: str, @@ -309,6 +491,79 @@ def create( :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( { "RoomSid": room_sid, @@ -321,17 +576,18 @@ def create( "Format": format, "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, - "Trim": trim, + "Trim": serialize.boolean_to_string(trim), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CompositionInstance(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, @@ -360,29 +616,59 @@ async def create_async( :returns: The created CompositionInstance """ - data = values.of( - { - "RoomSid": room_sid, - "VideoLayout": serialize.object(video_layout), - "AudioSources": serialize.map(audio_sources, lambda e: e), - "AudioSourcesExcluded": serialize.map( - audio_sources_excluded, lambda e: e - ), - "Resolution": resolution, - "Format": format, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "Trim": trim, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CompositionInstance(self._version, payload) + :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, @@ -462,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, @@ -489,6 +851,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -527,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( @@ -539,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, @@ -575,7 +1013,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CompositionPage(self._version, response) async def page_async( @@ -614,11 +1058,109 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 e15c43c4ac..16e7cb6f4a 100644 --- a/twilio/rest/video/v1/composition_hook.py +++ b/twilio/rest/video/v1/composition_hook.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class CompositionHookInstance(InstanceResource): + class Format(object): MP4 = "mp4" WEBM = "webm" @@ -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 @@ -226,6 +348,7 @@ def __repr__(self) -> str: class CompositionHookContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CompositionHookContext @@ -241,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 @@ -248,9 +385,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -260,9 +419,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CompositionHookInstance 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) -> CompositionHookInstance: @@ -272,17 +455,43 @@ def fetch(self) -> CompositionHookInstance: :returns: The fetched CompositionHookInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CompositionHookInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionHookInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CompositionHookInstance: """ @@ -291,19 +500,29 @@ async def fetch_async(self) -> CompositionHookInstance: :returns: The fetched CompositionHookInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CompositionHookInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CompositionHookInstance( + 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( + def _update( self, friendly_name: str, enabled: Union[bool, object] = values.unset, @@ -315,51 +534,86 @@ 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( { "FriendlyName": friendly_name, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "VideoLayout": serialize.object(video_layout), "AudioSources": serialize.map(audio_sources, lambda e: e), "AudioSourcesExcluded": serialize.map( audio_sources_excluded, lambda e: e ), - "Trim": trim, + "Trim": serialize.boolean_to_string(trim), "Format": format, "Resolution": resolution, "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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: 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, @@ -371,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. @@ -386,52 +640,181 @@ 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( { "FriendlyName": friendly_name, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "VideoLayout": serialize.object(video_layout), "AudioSources": serialize.map(audio_sources, lambda e: e), "AudioSourcesExcluded": serialize.map( audio_sources_excluded, lambda e: e ), - "Trim": trim, + "Trim": serialize.boolean_to_string(trim), "Format": format, "Resolution": resolution, "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CompositionHookInstance( - self._version, payload, sid=self._solution["sid"] - ) + headers["Accept"] = "application/json" - def __repr__(self) -> str: - """ - Provide a friendly representation + return await self._version.update_with_response_info_async( + method="POST", uri=self._uri, data=data, headers=headers + ) - :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 "".format(context) class CompositionHookPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CompositionHookInstance: """ Build an instance of CompositionHookInstance :param payload: Payload response from the API """ + return CompositionHookInstance(self._version, payload) def __repr__(self) -> str: @@ -444,6 +827,7 @@ def __repr__(self) -> str: class CompositionHookList(ListResource): + def __init__(self, version: Version): """ Initialize the CompositionHookList @@ -455,6 +839,52 @@ def __init__(self, version: Version): self._uri = "/CompositionHooks" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "Enabled": serialize.boolean_to_string(enabled), + "VideoLayout": serialize.object(video_layout), + "AudioSources": serialize.map(audio_sources, lambda e: e), + "AudioSourcesExcluded": serialize.map( + audio_sources_excluded, lambda e: e + ), + "Resolution": resolution, + "Format": format, + "StatusCallback": status_callback, + "StatusCallbackMethod": status_callback_method, + "Trim": serialize.boolean_to_string(trim), + } + ) + 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, @@ -484,10 +914,88 @@ def create( :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( { "FriendlyName": friendly_name, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "VideoLayout": serialize.object(video_layout), "AudioSources": serialize.map(audio_sources, lambda e: e), "AudioSourcesExcluded": serialize.map( @@ -497,17 +1005,18 @@ def create( "Format": format, "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, - "Trim": trim, + "Trim": serialize.boolean_to_string(trim), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CompositionHookInstance(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, @@ -538,30 +1047,63 @@ async def create_async( :returns: The created CompositionHookInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "Enabled": enabled, - "VideoLayout": serialize.object(video_layout), - "AudioSources": serialize.map(audio_sources, lambda e: e), - "AudioSourcesExcluded": serialize.map( - audio_sources_excluded, lambda e: e - ), - "Resolution": resolution, - "Format": format, - "StatusCallback": status_callback, - "StatusCallbackMethod": status_callback_method, - "Trim": trim, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CompositionHookInstance(self._version, payload) + :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, @@ -641,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, @@ -668,6 +1286,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( enabled=enabled, @@ -706,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( @@ -718,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, @@ -744,7 +1438,7 @@ def page( """ data = values.of( { - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), "FriendlyName": friendly_name, @@ -754,7 +1448,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CompositionHookPage(self._version, response) async def page_async( @@ -783,7 +1483,7 @@ async def page_async( """ data = values.of( { - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), "DateCreatedAfter": serialize.iso8601_datetime(date_created_after), "DateCreatedBefore": serialize.iso8601_datetime(date_created_before), "FriendlyName": friendly_name, @@ -793,11 +1493,109 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 42d10368d2..ec04358b3d 100644 --- a/twilio/rest/video/v1/composition_settings.py +++ b/twilio/rest/video/v1/composition_settings.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, Optional, Union -from twilio.base import values +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 @@ -22,12 +22,11 @@ class CompositionSettingsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the CompositionSettings resource. :ivar friendly_name: The string that you assigned to describe the resource and that will be shown in the console :ivar aws_credentials_sid: The SID of the stored Credential resource. - :ivar aws_s3_url: The URL of the AWS S3 bucket where the compositions are 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. + :ivar aws_s3_url: The URL of the AWS S3 bucket where the compositions are 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). :ivar aws_storage_enabled: Whether all compositions are written to the `aws_s3_url`. When `false`, all compositions are stored in our cloud. :ivar encryption_key_sid: The SID of the Public Key resource used for encryption. :ivar encryption_enabled: Whether all compositions are stored in an encrypted form. The default is `false`. @@ -77,7 +76,7 @@ def create( :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. + :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`. @@ -107,7 +106,7 @@ async def create_async( :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. + :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`. @@ -122,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 @@ -140,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 @@ -151,6 +228,7 @@ def __repr__(self) -> str: class CompositionSettingsContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the CompositionSettingsContext @@ -161,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, @@ -176,26 +290,89 @@ def create( :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. + :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: 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, "AwsCredentialsSid": aws_credentials_sid, "EncryptionKeySid": encryption_key_sid, "AwsS3Url": aws_s3_url, - "AwsStorageEnabled": aws_storage_enabled, - "EncryptionEnabled": encryption_enabled, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "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, @@ -212,28 +389,69 @@ async def create_async( :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. + :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: The created CompositionSettingsInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "AwsCredentialsSid": aws_credentials_sid, - "EncryptionKeySid": encryption_key_sid, - "AwsS3Url": aws_s3_url, - "AwsStorageEnabled": aws_storage_enabled, - "EncryptionEnabled": 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 + + :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 = 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) - return CompositionSettingsInstance(self._version, payload) + 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) -> CompositionSettingsInstance: """ @@ -242,16 +460,41 @@ def fetch(self) -> CompositionSettingsInstance: :returns: The fetched CompositionSettingsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CompositionSettingsInstance( + self._version, + payload, ) - return CompositionSettingsInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CompositionSettingsInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CompositionSettingsInstance: """ @@ -260,16 +503,25 @@ async def fetch_async(self) -> CompositionSettingsInstance: :returns: The fetched CompositionSettingsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CompositionSettingsInstance( + self._version, + payload, ) - return CompositionSettingsInstance( + 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: """ @@ -282,6 +534,7 @@ def __repr__(self) -> str: class CompositionSettingsList(ListResource): + def __init__(self, version: Version): """ Initialize the CompositionSettingsList diff --git a/twilio/rest/video/v1/recording.py b/twilio/rest/video/v1/recording.py index af0973776f..f99a8322dd 100644 --- a/twilio/rest/video/v1/recording.py +++ b/twilio/rest/video/v1/recording.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class RecordingInstance(InstanceResource): + class Codec(object): VP8 = "VP8" H264 = "H264" @@ -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 @@ -165,6 +203,7 @@ def __repr__(self) -> str: class RecordingContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the RecordingContext @@ -180,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 @@ -187,9 +240,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -199,9 +274,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + 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: @@ -211,17 +310,43 @@ def fetch(self) -> RecordingInstance: :returns: The fetched RecordingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RecordingInstance( + 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, 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) -> RecordingInstance: """ @@ -230,17 +355,27 @@ async def fetch_async(self) -> RecordingInstance: :returns: The fetched RecordingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return RecordingInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RecordingInstance( + 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: """ @@ -253,12 +388,14 @@ def __repr__(self) -> str: class RecordingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RecordingInstance: """ Build an instance of RecordingInstance :param payload: Payload response from the API """ + return RecordingInstance(self._version, payload) def __repr__(self) -> str: @@ -271,6 +408,7 @@ def __repr__(self) -> str: class RecordingList(ListResource): + def __init__(self, version: Version): """ Initialize the RecordingList @@ -372,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, @@ -403,6 +629,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -447,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( @@ -461,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, @@ -503,7 +817,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 RecordingPage(self._version, response) async def page_async( @@ -548,11 +868,121 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 2e3a4750f6..ce2373eb9f 100644 --- a/twilio/rest/video/v1/recording_settings.py +++ b/twilio/rest/video/v1/recording_settings.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, Optional, Union -from twilio.base import values +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 @@ -22,12 +22,11 @@ class RecordingSettingsInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RecordingSettings resource. :ivar friendly_name: The string that you assigned to describe the resource and show the user in the console :ivar aws_credentials_sid: The SID of the stored Credential resource. - :ivar aws_s3_url: The URL of the AWS S3 bucket where the recordings are 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. + :ivar aws_s3_url: The URL of the AWS S3 bucket where the recordings are 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). :ivar aws_storage_enabled: Whether all recordings are written to the `aws_s3_url`. When `false`, all recordings are stored in our cloud. :ivar encryption_key_sid: The SID of the Public Key resource used for encryption. :ivar encryption_enabled: Whether all recordings are stored in an encrypted form. The default is `false`. @@ -77,7 +76,7 @@ def create( :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. + :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`. @@ -107,7 +106,7 @@ async def create_async( :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. + :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`. @@ -122,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 @@ -140,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 @@ -151,6 +228,7 @@ def __repr__(self) -> str: class RecordingSettingsContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the RecordingSettingsContext @@ -161,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, @@ -176,26 +290,89 @@ def create( :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. + :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: 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, "AwsCredentialsSid": aws_credentials_sid, "EncryptionKeySid": encryption_key_sid, "AwsS3Url": aws_s3_url, - "AwsStorageEnabled": aws_storage_enabled, - "EncryptionEnabled": encryption_enabled, + "AwsStorageEnabled": serialize.boolean_to_string(aws_storage_enabled), + "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, @@ -212,28 +389,69 @@ async def create_async( :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. + :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: The created RecordingSettingsInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "AwsCredentialsSid": aws_credentials_sid, - "EncryptionKeySid": encryption_key_sid, - "AwsS3Url": aws_s3_url, - "AwsStorageEnabled": aws_storage_enabled, - "EncryptionEnabled": 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 + + :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 = 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) - return RecordingSettingsInstance(self._version, payload) + 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) -> RecordingSettingsInstance: """ @@ -242,16 +460,41 @@ def fetch(self) -> RecordingSettingsInstance: :returns: The fetched RecordingSettingsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RecordingSettingsInstance( + self._version, + payload, ) - return RecordingSettingsInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingSettingsInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RecordingSettingsInstance: """ @@ -260,16 +503,25 @@ async def fetch_async(self) -> RecordingSettingsInstance: :returns: The fetched RecordingSettingsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return RecordingSettingsInstance( + self._version, + payload, ) - return RecordingSettingsInstance( + 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: """ @@ -282,6 +534,7 @@ def __repr__(self) -> str: class RecordingSettingsList(ListResource): + def __init__(self, version: Version): """ Initialize the RecordingSettingsList diff --git a/twilio/rest/video/v1/room/__init__.py b/twilio/rest/video/v1/room/__init__.py index a3a4256590..cdc626b3e3 100644 --- a/twilio/rest/video/v1/room/__init__.py +++ b/twilio/rest/video/v1/room/__init__.py @@ -12,10 +12,10 @@ 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 @@ -24,18 +24,20 @@ 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): + class RoomStatus(object): IN_PROGRESS = "in-progress" COMPLETED = "completed" FAILED = "failed" class RoomType(object): + GROUP = "group" GO = "go" PEER_TO_PEER = "peer-to-peer" - GROUP = "group" GROUP_SMALL = "group-small" class VideoCodec(object): @@ -43,25 +45,25 @@ class VideoCodec(object): H264 = "H264" """ - :ivar sid: The unique string that we created to identify the Room resource. + :ivar sid: The unique string that Twilio created to identify the Room resource. :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 account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Room resource. :ivar enable_turn: Deprecated, now always considered to be true. :ivar 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`. - :ivar status_callback: The URL we 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. - :ivar status_callback_method: The HTTP method we use to call `status_callback`. Can be `POST` or `GET` and defaults to `POST`. + :ivar status_callback: The URL Twilio calls 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. + :ivar status_callback_method: The HTTP method Twilio uses to call `status_callback`. Can be `POST` or `GET` and defaults to `POST`. :ivar end_time: The UTC end time of the room in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601#UTC) format. :ivar duration: The duration of the room in seconds. :ivar type: :ivar max_participants: The maximum number of concurrent Participants allowed in the room. :ivar 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). :ivar max_concurrent_published_tracks: The maximum number of published audio, video, and data tracks all participants combined are allowed to publish in the room at the same time. Check [Programmable Video Limits](https://www.twilio.com/docs/video/programmable-video-limits) for more details. If it is set to 0 it means unconstrained. - :ivar record_participants_on_connect: Whether to start recording when Participants connect. ***This feature is not available in `peer-to-peer` rooms.*** - :ivar video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. ***This feature is not available in `peer-to-peer` rooms*** - :ivar media_region: The region for the media server in Group Rooms. Can be: one of the [available Media Regions](https://www.twilio.com/docs/video/ip-address-whitelisting#media-servers). ***This feature is not available in `peer-to-peer` rooms.*** - :ivar audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. Group rooms only. + :ivar record_participants_on_connect: Whether to start recording when Participants connect. + :ivar video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. + :ivar 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#media-servers). + :ivar audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. :ivar empty_room_timeout: Specifies how long (in minutes) a room will remain active after last participant leaves. Can be configured when creating a room via REST API. For Ad-Hoc rooms this value cannot be changed. :ivar unused_room_timeout: Specifies how long (in minutes) a room will remain active if no one joins. Can be configured when creating a room via REST API. For Ad-Hoc rooms this value cannot be changed. :ivar large_room: Indicates if this is a large room. @@ -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 @@ -215,6 +269,7 @@ def __repr__(self) -> str: class RoomContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the RoomContext @@ -233,6 +288,23 @@ 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) -> 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) -> RoomInstance: """ @@ -241,17 +313,43 @@ def fetch(self) -> RoomInstance: :returns: The fetched RoomInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RoomInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RoomInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RoomInstance: """ @@ -260,62 +358,122 @@ async def fetch_async(self) -> RoomInstance: :returns: The fetched RoomInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + 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( { "Status": status, } ) + 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, + 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( { "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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: "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: """ @@ -352,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 @@ -363,12 +533,14 @@ def __repr__(self) -> str: class RoomPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RoomInstance: """ Build an instance of RoomInstance :param payload: Payload response from the API """ + return RoomInstance(self._version, payload) def __repr__(self) -> str: @@ -381,6 +553,7 @@ def __repr__(self) -> str: class RoomList(ListResource): + def __init__(self, version: Version): """ Initialize the RoomList @@ -392,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, @@ -401,65 +574,62 @@ 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 we 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 we should use to call `status_callback`. Can be `POST` or `GET`. - :param max_participants: The maximum number of concurrent Participants allowed in the room. Peer-to-peer rooms can have up to 10 Participants. Small Group rooms can have up to 4 Participants. Group rooms can have up to 50 Participants. - :param record_participants_on_connect: Whether to start recording when Participants connect. ***This feature is not available in `peer-to-peer` rooms.*** - :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. ***This feature is not available in `peer-to-peer` rooms*** - :param media_region: The region for the media server in Group Rooms. Can be: one of the [available Media Regions](https://www.twilio.com/docs/video/ip-address-whitelisting#group-rooms-media-servers). ***This feature is not available in `peer-to-peer` rooms.*** - :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. Group rooms only. - :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( { - "EnableTurn": enable_turn, + "EnableTurn": serialize.boolean_to_string(enable_turn), "Type": type, "UniqueName": unique_name, "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, "MaxParticipants": max_participants, - "RecordParticipantsOnConnect": record_participants_on_connect, + "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), - "AudioOnly": audio_only, + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), + "AudioOnly": serialize.boolean_to_string(audio_only), "MaxParticipantDuration": max_participant_duration, "EmptyRoomTimeout": empty_room_timeout, "UnusedRoomTimeout": unused_room_timeout, - "LargeRoom": large_room, + "LargeRoom": serialize.boolean_to_string(large_room), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RoomInstance(self._version, payload) + headers["Accept"] = "application/json" - async def create_async( + return self._version.create_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + + def create( self, enable_turn: Union[bool, object] = values.unset, type: Union["RoomInstance.RoomType", object] = values.unset, @@ -468,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, @@ -478,19 +650,21 @@ 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: :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 we 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 we should use to call `status_callback`. Can be `POST` or `GET`. - :param max_participants: The maximum number of concurrent Participants allowed in the room. Peer-to-peer rooms can have up to 10 Participants. Small Group rooms can have up to 4 Participants. Group rooms can have up to 50 Participants. - :param record_participants_on_connect: Whether to start recording when Participants connect. ***This feature is not available in `peer-to-peer` rooms.*** - :param video_codecs: An array of the video codecs that are supported when publishing a track in the room. Can be: `VP8` and `H264`. ***This feature is not available in `peer-to-peer` rooms*** - :param media_region: The region for the media server in Group Rooms. Can be: one of the [available Media Regions](https://www.twilio.com/docs/video/ip-address-whitelisting#group-rooms-media-servers). ***This feature is not available in `peer-to-peer` rooms.*** + :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 audio_only: When set to true, indicates that the participants in the room will only publish audio. No video tracks will be allowed. Group rooms only. + :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). @@ -498,34 +672,285 @@ 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( { - "EnableTurn": enable_turn, + "EnableTurn": serialize.boolean_to_string(enable_turn), "Type": type, "UniqueName": unique_name, "StatusCallback": status_callback, "StatusCallbackMethod": status_callback_method, "MaxParticipants": max_participants, - "RecordParticipantsOnConnect": record_participants_on_connect, + "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), - "AudioOnly": audio_only, + "TranscriptionsConfiguration": serialize.object( + transcriptions_configuration + ), + "AudioOnly": serialize.boolean_to_string(audio_only), "MaxParticipantDuration": max_participant_duration, "EmptyRoomTimeout": empty_room_timeout, "UnusedRoomTimeout": unused_room_timeout, - "LargeRoom": large_room, + "LargeRoom": serialize.boolean_to_string(large_room), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -604,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, @@ -631,6 +1132,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -669,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( @@ -681,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, @@ -717,7 +1294,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 RoomPage(self._version, response) async def page_async( @@ -756,11 +1339,109 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 f8a21ba6a1..fdee154a0c 100644 --- a/twilio/rest/video/v1/room/participant/__init__.py +++ b/twilio/rest/video/v1/room/participant/__init__.py @@ -12,10 +12,10 @@ 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 @@ -28,9 +28,11 @@ 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: """ @@ -184,6 +233,7 @@ def __repr__(self) -> str: class ParticipantContext(InstanceContext): + def __init__(self, version: Version, room_sid: str, sid: str): """ Initialize the ParticipantContext @@ -206,6 +256,22 @@ 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) -> 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 @@ -213,18 +279,45 @@ def fetch(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], ) - return ParticipantInstance( + 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, 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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ParticipantInstance: """ @@ -233,41 +326,66 @@ async def fetch_async(self) -> ParticipantInstance: :returns: The fetched ParticipantInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ParticipantInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], ) - return ParticipantInstance( + 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"], sid=self._solution["sid"], ) + return ApiResponse(data=instance, status_code=status_code, headers=headers) - def update( + def _update( self, status: Union["ParticipantInstance.Status", object] = values.unset - ) -> ParticipantInstance: + ) -> tuple: """ - Update the ParticipantInstance + Internal helper for update operation - :param status: - - :returns: The updated ParticipantInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "Status": status, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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["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, @@ -275,28 +393,61 @@ 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( { "Status": status, } ) + headers = values.of({}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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["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, @@ -304,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: """ @@ -367,12 +537,14 @@ def __repr__(self) -> str: class ParticipantPage(Page): + 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, room_sid=self._solution["room_sid"] ) @@ -387,6 +559,7 @@ def __repr__(self) -> str: class ParticipantList(ListResource): + def __init__(self, version: Version, room_sid: str): """ Initialize the ParticipantList @@ -481,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, @@ -508,6 +757,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -546,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( @@ -558,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, @@ -594,8 +919,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ParticipantPage(self._version, response, self._solution) + 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, solution=self._solution) async def page_async( self, @@ -633,10 +964,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return ParticipantPage(self._version, response, self._solution) + 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: """ @@ -648,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: """ @@ -660,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 415c5b1f20..4a024d06a2 100644 --- a/twilio/rest/video/v1/room/participant/anonymize.py +++ b/twilio/rest/video/v1/room/participant/anonymize.py @@ -12,10 +12,10 @@ 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 @@ -23,6 +23,7 @@ class AnonymizeInstance(InstanceResource): + class Status(object): CONNECTED = "connected" DISCONNECTED = "disconnected" @@ -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 @@ -117,6 +137,7 @@ def __repr__(self) -> str: class AnonymizeContext(InstanceContext): + def __init__(self, version: Version, room_sid: str, sid: str): """ Initialize the AnonymizeContext @@ -136,6 +157,23 @@ def __init__(self, version: Version, room_sid: str, sid: str): **self._solution ) + def _update(self) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of({}) + headers = values.of({}) + + headers["Accept"] = "application/json" + + return self._version.update_with_response_info( + method="POST", uri=self._uri, data=data, headers=headers + ) + def update(self) -> AnonymizeInstance: """ Update the AnonymizeInstance @@ -143,20 +181,46 @@ def update(self) -> AnonymizeInstance: :returns: The updated AnonymizeInstance """ - data = values.of({}) - - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + payload, _, _ = self._update() + return AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], ) - return AnonymizeInstance( + def update_with_http_info(self) -> ApiResponse: + """ + Update the AnonymizeInstance and return response metadata + + + :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({}) + headers = values.of({}) + + 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) -> AnonymizeInstance: """ @@ -165,20 +229,29 @@ async def update_async(self) -> AnonymizeInstance: :returns: The updated AnonymizeInstance """ - data = values.of({}) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + payload, _, _ = await self._update_async() + return AnonymizeInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], ) - return AnonymizeInstance( + 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: """ @@ -191,6 +264,7 @@ def __repr__(self) -> str: class AnonymizeList(ListResource): + def __init__(self, version: Version, room_sid: str, sid: str): """ Initialize the AnonymizeList diff --git a/twilio/rest/video/v1/room/participant/published_track.py b/twilio/rest/video/v1/room/participant/published_track.py index a5156fee8f..ec1ebf09a4 100644 --- a/twilio/rest/video/v1/room/participant/published_track.py +++ b/twilio/rest/video/v1/room/participant/published_track.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class PublishedTrackInstance(InstanceResource): + class Kind(object): AUDIO = "audio" VIDEO = "video" @@ -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 @@ -118,6 +138,7 @@ def __repr__(self) -> str: class PublishedTrackContext(InstanceContext): + def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: str): """ Initialize the PublishedTrackContext @@ -139,6 +160,22 @@ def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: s **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) -> PublishedTrackInstance: """ Fetch the PublishedTrackInstance @@ -146,19 +183,47 @@ def fetch(self) -> PublishedTrackInstance: :returns: The fetched PublishedTrackInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], ) - return PublishedTrackInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the PublishedTrackInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> PublishedTrackInstance: """ @@ -167,19 +232,31 @@ async def fetch_async(self) -> PublishedTrackInstance: :returns: The fetched PublishedTrackInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return PublishedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], ) - return PublishedTrackInstance( + 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: """ @@ -192,12 +269,14 @@ def __repr__(self) -> str: class PublishedTrackPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> PublishedTrackInstance: """ Build an instance of PublishedTrackInstance :param payload: Payload response from the API """ + return PublishedTrackInstance( self._version, payload, @@ -215,6 +294,7 @@ def __repr__(self) -> str: class PublishedTrackList(ListResource): + def __init__(self, version: Version, room_sid: str, participant_sid: str): """ Initialize the PublishedTrackList @@ -287,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, @@ -306,6 +436,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -332,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( @@ -340,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, @@ -364,8 +546,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return PublishedTrackPage(self._version, response, self._solution) + 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 PublishedTrackPage(self._version, response, solution=self._solution) async def page_async( self, @@ -391,10 +579,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return PublishedTrackPage(self._version, response, self._solution) + 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: """ @@ -406,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: """ @@ -418,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 28e3976d15..f13f7e6473 100644 --- a/twilio/rest/video/v1/room/participant/subscribe_rules.py +++ b/twilio/rest/video/v1/room/participant/subscribe_rules.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,7 +23,6 @@ class SubscribeRulesInstance(InstanceResource): - """ :ivar participant_sid: The SID of the Participant resource for the Subscribe Rules. :ivar room_sid: The SID of the Room resource for the Subscribe Rules @@ -67,6 +66,7 @@ def __repr__(self) -> str: class SubscribeRulesList(ListResource): + def __init__(self, version: Version, room_sid: str, participant_sid: str): """ Initialize the SubscribeRulesList @@ -89,14 +89,29 @@ def __init__(self, version: Version, room_sid: str, participant_sid: str): ) ) + 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) -> SubscribeRulesInstance: """ - Asynchronously fetch the SubscribeRulesInstance + Fetch the SubscribeRulesInstance + :returns: The fetched SubscribeRulesInstance """ - payload = self._version.fetch(method="GET", uri=self._uri) - + payload, _, _ = self._fetch() return SubscribeRulesInstance( self._version, payload, @@ -104,14 +119,45 @@ def fetch(self) -> SubscribeRulesInstance: participant_sid=self._solution["participant_sid"], ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribeRulesInstance and return response metadata + + + :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" + + 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._version.fetch_async(method="GET", uri=self._uri) - + payload, _, _ = await self._fetch_async() return SubscribeRulesInstance( self._version, payload, @@ -119,28 +165,56 @@ 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( { "Rules": serialize.object(rules), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -148,28 +222,59 @@ 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( { "Rules": serialize.object(rules), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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, @@ -177,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 627015a44a..de2ef19592 100644 --- a/twilio/rest/video/v1/room/participant/subscribed_track.py +++ b/twilio/rest/video/v1/room/participant/subscribed_track.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class SubscribedTrackInstance(InstanceResource): + class Kind(object): AUDIO = "audio" VIDEO = "video" @@ -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 @@ -120,6 +140,7 @@ def __repr__(self) -> str: class SubscribedTrackContext(InstanceContext): + def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: str): """ Initialize the SubscribedTrackContext @@ -141,6 +162,22 @@ def __init__(self, version: Version, room_sid: str, participant_sid: str, sid: s **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) -> SubscribedTrackInstance: """ Fetch the SubscribedTrackInstance @@ -148,19 +185,47 @@ def fetch(self) -> SubscribedTrackInstance: :returns: The fetched SubscribedTrackInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], ) - return SubscribedTrackInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SubscribedTrackInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SubscribedTrackInstance: """ @@ -169,19 +234,31 @@ async def fetch_async(self) -> SubscribedTrackInstance: :returns: The fetched SubscribedTrackInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SubscribedTrackInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + participant_sid=self._solution["participant_sid"], + sid=self._solution["sid"], ) - return SubscribedTrackInstance( + 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: """ @@ -194,12 +271,14 @@ def __repr__(self) -> str: class SubscribedTrackPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SubscribedTrackInstance: """ Build an instance of SubscribedTrackInstance :param payload: Payload response from the API """ + return SubscribedTrackInstance( self._version, payload, @@ -217,6 +296,7 @@ def __repr__(self) -> str: class SubscribedTrackList(ListResource): + def __init__(self, version: Version, room_sid: str, participant_sid: str): """ Initialize the SubscribedTrackList @@ -289,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, @@ -308,6 +438,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -334,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( @@ -342,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, @@ -366,8 +548,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return SubscribedTrackPage(self._version, response, self._solution) + 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 SubscribedTrackPage(self._version, response, solution=self._solution) async def page_async( self, @@ -393,10 +581,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return SubscribedTrackPage(self._version, response, self._solution) + 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: """ @@ -408,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: """ @@ -420,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 68adaed070..d399cd03d4 100644 --- a/twilio/rest/video/v1/room/recording_rules.py +++ b/twilio/rest/video/v1/room/recording_rules.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -23,7 +23,6 @@ class RecordingRulesInstance(InstanceResource): - """ :ivar room_sid: The SID of the Room resource for the Recording Rules :ivar rules: A collection of Recording Rules that describe how to include or exclude matching tracks for recording @@ -58,6 +57,7 @@ def __repr__(self) -> str: class RecordingRulesList(ListResource): + def __init__(self, version: Version, room_sid: str): """ Initialize the RecordingRulesList @@ -74,82 +74,194 @@ def __init__(self, version: Version, room_sid: str): } self._uri = "/Rooms/{room_sid}/RecordingRules".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) -> RecordingRulesInstance: """ - Asynchronously fetch the RecordingRulesInstance + Fetch the RecordingRulesInstance + :returns: The fetched RecordingRulesInstance """ - payload = self._version.fetch(method="GET", uri=self._uri) - + payload, _, _ = self._fetch() return RecordingRulesInstance( self._version, payload, room_sid=self._solution["room_sid"] ) + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RecordingRulesInstance and return response metadata + + + :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" + + 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._version.fetch_async(method="GET", uri=self._uri) - + 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( { "Rules": serialize.object(rules), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, 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( { "Rules": serialize.object(rules), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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 481422eacb..697904b713 100644 --- a/twilio/rest/video/v1/room/room_recording.py +++ b/twilio/rest/video/v1/room/room_recording.py @@ -12,10 +12,10 @@ 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 @@ -24,6 +24,7 @@ class RoomRecordingInstance(InstanceResource): + class Codec(object): VP8 = "VP8" H264 = "H264" @@ -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 @@ -167,6 +205,7 @@ def __repr__(self) -> str: class RoomRecordingContext(InstanceContext): + def __init__(self, version: Version, room_sid: str, sid: str): """ Initialize the RoomRecordingContext @@ -184,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 @@ -191,9 +244,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -203,9 +278,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RoomRecordingInstance 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) -> RoomRecordingInstance: @@ -215,18 +314,45 @@ def fetch(self) -> RoomRecordingInstance: :returns: The fetched RoomRecordingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], ) - return RoomRecordingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RoomRecordingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RoomRecordingInstance: """ @@ -235,18 +361,29 @@ async def fetch_async(self) -> RoomRecordingInstance: :returns: The fetched RoomRecordingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return RoomRecordingInstance( + self._version, + payload, + room_sid=self._solution["room_sid"], + sid=self._solution["sid"], ) - return RoomRecordingInstance( + 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: """ @@ -259,12 +396,14 @@ def __repr__(self) -> str: class RoomRecordingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RoomRecordingInstance: """ Build an instance of RoomRecordingInstance :param payload: Payload response from the API """ + return RoomRecordingInstance( self._version, payload, room_sid=self._solution["room_sid"] ) @@ -279,6 +418,7 @@ def __repr__(self) -> str: class RoomRecordingList(ListResource): + def __init__(self, version: Version, room_sid: str): """ Initialize the RoomRecordingList @@ -373,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, @@ -400,6 +616,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -438,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( @@ -450,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, @@ -486,8 +778,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return RoomRecordingPage(self._version, response, self._solution) + 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 RoomRecordingPage(self._version, response, solution=self._solution) async def page_async( self, @@ -525,10 +823,108 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return RoomRecordingPage(self._version, response, self._solution) + 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: """ @@ -540,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: """ @@ -552,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 "".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 "".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 "" + + +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 "" diff --git a/twilio/rest/voice/VoiceBase.py b/twilio/rest/voice/VoiceBase.py index 21a11ce350..3bcc12e228 100644 --- a/twilio/rest/voice/VoiceBase.py +++ b/twilio/rest/voice/VoiceBase.py @@ -14,9 +14,11 @@ from twilio.base.domain import Domain from twilio.rest import Client from twilio.rest.voice.v1 import V1 +from twilio.rest.voice.v3 import V3 class VoiceBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Voice Domain @@ -25,6 +27,7 @@ def __init__(self, twilio: Client): """ super().__init__(twilio, "https://voice.twilio.com") self._v1: Optional[V1] = None + self._v3: Optional[V3] = None @property def v1(self) -> V1: @@ -35,6 +38,15 @@ def v1(self) -> V1: self._v1 = V1(self) return self._v1 + @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/__init__.py b/twilio/rest/voice/v1/__init__.py index 2014cd1626..75c0c7fc74 100644 --- a/twilio/rest/voice/v1/__init__.py +++ b/twilio/rest/voice/v1/__init__.py @@ -24,6 +24,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Voice diff --git a/twilio/rest/voice/v1/archived_call.py b/twilio/rest/voice/v1/archived_call.py index de13e682da..090f21d452 100644 --- a/twilio/rest/voice/v1/archived_call.py +++ b/twilio/rest/voice/v1/archived_call.py @@ -12,8 +12,9 @@ Do not edit the class manually. """ - 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 @@ -21,6 +22,7 @@ class ArchivedCallContext(InstanceContext): + def __init__(self, version: Version, date: date, sid: str): """ Initialize the ArchivedCallContext @@ -38,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 @@ -45,9 +61,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -57,10 +95,18 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, - ) + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ArchivedCallInstance 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 __repr__(self) -> str: """ @@ -73,6 +119,7 @@ def __repr__(self) -> str: class ArchivedCallList(ListResource): + def __init__(self, version: Version): """ Initialize the ArchivedCallList diff --git a/twilio/rest/voice/v1/byoc_trunk.py b/twilio/rest/voice/v1/byoc_trunk.py index 88ed49dcbc..f6e053c0dc 100644 --- a/twilio/rest/voice/v1/byoc_trunk.py +++ b/twilio/rest/voice/v1/byoc_trunk.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class ByocTrunkInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the BYOC Trunk resource. :ivar sid: The unique string that that we created to identify the BYOC Trunk resource. @@ -73,6 +72,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ByocTrunkContext] = None @property @@ -108,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 @@ -126,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, @@ -210,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 @@ -221,6 +341,7 @@ def __repr__(self) -> str: class ByocTrunkContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ByocTrunkContext @@ -236,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 @@ -243,9 +378,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -255,9 +412,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ByocTrunkInstance 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) -> ByocTrunkInstance: @@ -267,17 +448,43 @@ def fetch(self) -> ByocTrunkInstance: :returns: The fetched ByocTrunkInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ByocTrunkInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ByocTrunkInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ByocTrunkInstance: """ @@ -286,19 +493,29 @@ async def fetch_async(self) -> ByocTrunkInstance: :returns: The fetched ByocTrunkInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ByocTrunkInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ByocTrunkInstance( + 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( + def _update( self, friendly_name: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -310,23 +527,14 @@ 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( { "FriendlyName": friendly_name, @@ -336,21 +544,22 @@ def update( "VoiceFallbackMethod": voice_fallback_method, "StatusCallbackUrl": status_callback_url, "StatusCallbackMethod": status_callback_method, - "CnamLookupEnabled": cnam_lookup_enabled, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), "ConnectionPolicySid": connection_policy_sid, "FromDomainSid": from_domain_sid, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ByocTrunkInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - async def update_async( + 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, voice_url: Union[str, object] = values.unset, @@ -364,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. @@ -379,70 +588,21 @@ async def update_async( :returns: The updated ByocTrunkInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - "VoiceUrl": voice_url, - "VoiceMethod": voice_method, - "VoiceFallbackUrl": voice_fallback_url, - "VoiceFallbackMethod": voice_fallback_method, - "StatusCallbackUrl": status_callback_url, - "StatusCallbackMethod": status_callback_method, - "CnamLookupEnabled": cnam_lookup_enabled, - "ConnectionPolicySid": connection_policy_sid, - "FromDomainSid": from_domain_sid, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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 __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 ByocTrunkPage(Page): - def get_instance(self, payload: Dict[str, Any]) -> ByocTrunkInstance: - """ - Build an instance of ByocTrunkInstance - - :param payload: Payload response from the API - """ - return ByocTrunkInstance(self._version, payload) - - def __repr__(self) -> str: - """ - Provide a friendly representation - - :returns: Machine friendly representation - """ - return "" - - -class ByocTrunkList(ListResource): - def __init__(self, version: Version): - """ - Initialize the ByocTrunkList - - :param version: Version that contains the resource - - """ - super().__init__(version) - - self._uri = "/ByocTrunks" - - def create( + def update_with_http_info( self, friendly_name: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -454,14 +614,14 @@ 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: + ) -> ApiResponse: """ - Create the ByocTrunkInstance + 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`. 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_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`. @@ -469,32 +629,242 @@ def create( :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 + :returns: ApiResponse with instance, status code, and headers """ - data = values.of( - { - "FriendlyName": friendly_name, + 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( + { + "FriendlyName": friendly_name, "VoiceUrl": voice_url, "VoiceMethod": voice_method, "VoiceFallbackUrl": voice_fallback_url, "VoiceFallbackMethod": voice_fallback_method, "StatusCallbackUrl": status_callback_url, "StatusCallbackMethod": status_callback_method, - "CnamLookupEnabled": cnam_lookup_enabled, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), "ConnectionPolicySid": connection_policy_sid, "FromDomainSid": from_domain_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_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"]) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + 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 "".format(context) + + +class ByocTrunkPage(Page): + + def get_instance(self, payload: Dict[str, Any]) -> ByocTrunkInstance: + """ + Build an instance of ByocTrunkInstance + + :param payload: Payload response from the API + """ return ByocTrunkInstance(self._version, payload) - async def create_async( + def __repr__(self) -> str: + """ + Provide a friendly representation + + :returns: Machine friendly representation + """ + return "" + + +class ByocTrunkList(ListResource): + + def __init__(self, version: Version): + """ + Initialize the ByocTrunkList + + :param version: Version that contains the resource + + """ + super().__init__(version) + + self._uri = "/ByocTrunks" + + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + "VoiceUrl": voice_url, + "VoiceMethod": voice_method, + "VoiceFallbackUrl": voice_fallback_url, + "VoiceFallbackMethod": voice_fallback_method, + "StatusCallbackUrl": status_callback_url, + "StatusCallbackMethod": status_callback_method, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), + "ConnectionPolicySid": connection_policy_sid, + "FromDomainSid": from_domain_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, friendly_name: Union[str, object] = values.unset, voice_url: Union[str, object] = values.unset, @@ -508,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. @@ -523,6 +893,84 @@ 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( { "FriendlyName": friendly_name, @@ -532,20 +980,108 @@ async def create_async( "VoiceFallbackMethod": voice_fallback_method, "StatusCallbackUrl": status_callback_url, "StatusCallbackMethod": status_callback_method, - "CnamLookupEnabled": cnam_lookup_enabled, + "CnamLookupEnabled": serialize.boolean_to_string(cnam_lookup_enabled), "ConnectionPolicySid": connection_policy_sid, "FromDomainSid": from_domain_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -596,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, @@ -615,6 +1201,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -641,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( @@ -649,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, @@ -673,7 +1311,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 ByocTrunkPage(self._version, response) async def page_async( @@ -700,11 +1344,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 e1c26dc495..2d8d1ac47e 100644 --- a/twilio/rest/voice/v1/connection_policy/__init__.py +++ b/twilio/rest/voice/v1/connection_policy/__init__.py @@ -12,10 +12,10 @@ 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 @@ -27,7 +27,6 @@ class ConnectionPolicyInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Connection Policy resource. :ivar sid: The unique string that we created to identify the Connection Policy resource. @@ -58,6 +57,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[ConnectionPolicyContext] = None @property @@ -93,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 @@ -111,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": @@ -139,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: """ @@ -157,6 +221,7 @@ def __repr__(self) -> str: class ConnectionPolicyContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the ConnectionPolicyContext @@ -174,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 @@ -181,9 +260,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -193,9 +294,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyInstance 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) -> ConnectionPolicyInstance: @@ -205,17 +330,43 @@ def fetch(self) -> ConnectionPolicyInstance: :returns: The fetched ConnectionPolicyInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ConnectionPolicyInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ConnectionPolicyInstance: """ @@ -224,17 +375,50 @@ async def fetch_async(self) -> ConnectionPolicyInstance: :returns: The fetched ConnectionPolicyInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ConnectionPolicyInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return ConnectionPolicyInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the ConnectionPolicyInstance and return response metadata + + + :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( + { + "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, friendly_name: Union[str, object] = values.unset @@ -246,20 +430,50 @@ def update( :returns: The updated ConnectionPolicyInstance """ + payload, _, _ = self._update(friendly_name=friendly_name) + return ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] + ) + + def update_with_http_info( + self, friendly_name: Union[str, object] = values.unset + ) -> ApiResponse: + """ + 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 = 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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ConnectionPolicyInstance( - self._version, payload, sid=self._solution["sid"] + 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( @@ -272,21 +486,28 @@ async def update_async( :returns: The updated ConnectionPolicyInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - } + payload, _, _ = await self._update_async(friendly_name=friendly_name) + return ConnectionPolicyInstance( + self._version, payload, sid=self._solution["sid"] ) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return 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: 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: @@ -311,12 +532,14 @@ def __repr__(self) -> str: class ConnectionPolicyPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyInstance: """ Build an instance of ConnectionPolicyInstance :param payload: Payload response from the API """ + return ConnectionPolicyInstance(self._version, payload) def __repr__(self) -> str: @@ -329,6 +552,7 @@ def __repr__(self) -> str: class ConnectionPolicyList(ListResource): + def __init__(self, version: Version): """ Initialize the ConnectionPolicyList @@ -340,6 +564,29 @@ def __init__(self, version: Version): self._uri = "/ConnectionPolicies" + def _create(self, friendly_name: Union[str, object] = values.unset) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "FriendlyName": friendly_name, + } + ) + 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 ) -> ConnectionPolicyInstance: @@ -350,19 +597,47 @@ def create( :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( { "FriendlyName": friendly_name, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return ConnectionPolicyInstance(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, friendly_name: Union[str, object] = values.unset @@ -374,19 +649,24 @@ async def create_async( :returns: The created ConnectionPolicyInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - } - ) + payload, _, _ = await self._create_async(friendly_name=friendly_name) + return ConnectionPolicyInstance(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: Union[str, object] = values.unset + ) -> ApiResponse: + """ + Asynchronously create the ConnectionPolicyInstance and return response metadata - return ConnectionPolicyInstance(self._version, payload) + :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, @@ -438,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, @@ -457,6 +787,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -483,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( @@ -491,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, @@ -515,7 +897,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 ConnectionPolicyPage(self._version, response) async def page_async( @@ -542,11 +930,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 e617072cb2..2f84ce2e4d 100644 --- a/twilio/rest/voice/v1/connection_policy/connection_policy_target.py +++ b/twilio/rest/voice/v1/connection_policy/connection_policy_target.py @@ -12,10 +12,10 @@ 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 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,7 +24,6 @@ class ConnectionPolicyTargetInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Target resource. :ivar connection_policy_sid: The SID of the Connection Policy that owns the Target. @@ -68,6 +67,7 @@ def __init__( "connection_policy_sid": connection_policy_sid, "sid": sid or self.sid, } + self._context: Optional[ConnectionPolicyTargetContext] = None @property @@ -104,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 @@ -122,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, @@ -176,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 @@ -187,6 +277,7 @@ def __repr__(self) -> str: class ConnectionPolicyTargetContext(InstanceContext): + def __init__(self, version: Version, connection_policy_sid: str, sid: str): """ Initialize the ConnectionPolicyTargetContext @@ -206,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 @@ -213,9 +318,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -225,9 +352,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the ConnectionPolicyTargetInstance 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) -> ConnectionPolicyTargetInstance: @@ -237,18 +388,45 @@ def fetch(self) -> ConnectionPolicyTargetInstance: :returns: The fetched ConnectionPolicyTargetInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], ) - return ConnectionPolicyTargetInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the ConnectionPolicyTargetInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> ConnectionPolicyTargetInstance: """ @@ -257,54 +435,90 @@ async def fetch_async(self) -> ConnectionPolicyTargetInstance: :returns: The fetched ConnectionPolicyTargetInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return ConnectionPolicyTargetInstance( + self._version, + payload, + connection_policy_sid=self._solution["connection_policy_sid"], + sid=self._solution["sid"], ) - return ConnectionPolicyTargetInstance( + 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( + 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 - - :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. + Internal helper for update operation - :returns: The updated ConnectionPolicyTargetInstance + Returns: + tuple: (payload, status_code, headers) """ + data = values.of( { "FriendlyName": friendly_name, "Target": target, "Priority": priority, "Weight": weight, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -312,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. @@ -329,24 +543,83 @@ 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( { "FriendlyName": friendly_name, "Target": target, "Priority": priority, "Weight": weight, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(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, + 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, @@ -354,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 @@ -365,12 +672,14 @@ def __repr__(self) -> str: class ConnectionPolicyTargetPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> ConnectionPolicyTargetInstance: """ Build an instance of ConnectionPolicyTargetInstance :param payload: Payload response from the API """ + return ConnectionPolicyTargetInstance( self._version, payload, @@ -387,6 +696,7 @@ def __repr__(self) -> str: class ConnectionPolicyTargetList(ListResource): + def __init__(self, version: Version, connection_policy_sid: str): """ Initialize the ConnectionPolicyTargetList @@ -405,57 +715,82 @@ 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( { "Target": target, "FriendlyName": friendly_name, "Priority": priority, "Weight": weight, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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. @@ -463,30 +798,121 @@ 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( { "Target": target, "FriendlyName": friendly_name, "Priority": priority, "Weight": weight, - "Enabled": enabled, + "Enabled": serialize.boolean_to_string(enabled), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -537,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, @@ -556,6 +1032,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -582,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( @@ -590,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, @@ -614,8 +1142,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return ConnectionPolicyTargetPage(self._version, response, self._solution) + 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 ConnectionPolicyTargetPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -641,10 +1177,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + return ConnectionPolicyTargetPage( + self._version, response, solution=self._solution ) - return ConnectionPolicyTargetPage(self._version, response, 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: """ @@ -656,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: """ @@ -668,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/__init__.py b/twilio/rest/voice/v1/dialing_permissions/__init__.py index 2de126841e..2346430adc 100644 --- a/twilio/rest/voice/v1/dialing_permissions/__init__.py +++ b/twilio/rest/voice/v1/dialing_permissions/__init__.py @@ -12,7 +12,6 @@ Do not edit the class manually. """ - from typing import Optional @@ -27,6 +26,7 @@ class DialingPermissionsList(ListResource): + def __init__(self, version: Version): """ Initialize the DialingPermissionsList 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 3e4966c72e..fc4a80d633 100644 --- a/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py +++ b/twilio/rest/voice/v1/dialing_permissions/bulk_country_update.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - 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 @@ -22,7 +22,6 @@ class BulkCountryUpdateInstance(InstanceResource): - """ :ivar update_count: The number of countries updated :ivar update_request: A bulk update request to change voice dialing country permissions stored as a URL-encoded, JSON array of update objects. For example : `[ { \"iso_code\": \"GB\", \"low_risk_numbers_enabled\": \"true\", \"high_risk_special_numbers_enabled\":\"true\", \"high_risk_tollfraud_numbers_enabled\": \"false\" } ]` @@ -47,6 +46,7 @@ def __repr__(self) -> str: class BulkCountryUpdateList(ListResource): + def __init__(self, version: Version): """ Initialize the BulkCountryUpdateList @@ -58,50 +58,100 @@ 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( { "UpdateRequest": update_request, } ) + 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, + 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( { "UpdateRequest": update_request, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, 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 fa1ad785b5..ed666a1eb8 100644 --- a/twilio/rest/voice/v1/dialing_permissions/country/__init__.py +++ b/twilio/rest/voice/v1/dialing_permissions/country/__init__.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, List, Optional, Union, Iterator, AsyncIterator -from twilio.base import values +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 @@ -26,7 +26,6 @@ class CountryInstance(InstanceResource): - """ :ivar iso_code: The [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). :ivar name: The name of the country. @@ -34,7 +33,7 @@ class CountryInstance(InstanceResource): :ivar country_codes: The E.164 assigned [country codes(s)](https://www.itu.int/itudoc/itu-t/ob-lists/icc/e164_763.html) :ivar low_risk_numbers_enabled: Whether dialing to low-risk numbers is enabled. :ivar high_risk_special_numbers_enabled: Whether dialing to high-risk special services numbers is enabled. These prefixes include number ranges allocated by the country and include premium numbers, special services, shared cost, and others - :ivar high_risk_tollfraud_numbers_enabled: Whether dialing to high-risk [toll fraud](https://www.twilio.com/learn/voice-and-video/toll-fraud) numbers is enabled. These prefixes include narrow number ranges that have a high-risk of international revenue sharing fraud (IRSF) attacks, also known as [toll fraud](https://www.twilio.com/learn/voice-and-video/toll-fraud). These prefixes are collected from anti-fraud databases and verified by analyzing calls on our network. These prefixes are not available for download and are updated frequently + :ivar high_risk_tollfraud_numbers_enabled: Whether 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 is enabled. These prefixes include narrow number ranges that have a high-risk of international revenue sharing fraud (IRSF) attacks, also known as [toll fraud](https://www.twilio.com/blog/how-to-protect-your-account-from-toll-fraud-with-voice-dialing-geo-permissions-html). These prefixes are collected from anti-fraud databases and verified by analyzing calls on our network. These prefixes are not available for download and are updated frequently :ivar url: The absolute URL of this resource. :ivar links: A list of URLs related to this resource. """ @@ -63,6 +62,7 @@ def __init__( self._solution = { "iso_code": iso_code or self.iso_code, } + self._context: Optional[CountryContext] = None @property @@ -98,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: """ @@ -116,6 +134,7 @@ def __repr__(self) -> str: class CountryContext(InstanceContext): + def __init__(self, version: Version, iso_code: str): """ Initialize the CountryContext @@ -133,6 +152,22 @@ def __init__(self, version: Version, iso_code: str): self._highrisk_special_prefixes: Optional[HighriskSpecialPrefixList] = None + 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) -> CountryInstance: """ Fetch the CountryInstance @@ -140,17 +175,43 @@ def fetch(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], ) - return CountryInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CountryInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CountryInstance: """ @@ -159,17 +220,27 @@ async def fetch_async(self) -> CountryInstance: :returns: The fetched CountryInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CountryInstance( + self._version, + payload, + iso_code=self._solution["iso_code"], ) - return CountryInstance( + 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: @@ -194,12 +265,14 @@ def __repr__(self) -> str: class CountryPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CountryInstance: """ Build an instance of CountryInstance :param payload: Payload response from the API """ + return CountryInstance(self._version, payload) def __repr__(self) -> str: @@ -212,6 +285,7 @@ def __repr__(self) -> str: class CountryList(ListResource): + def __init__(self, version: Version): """ Initialize the CountryList @@ -245,7 +319,7 @@ def stream( :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/learn/voice-and-video/toll-fraud) 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 @@ -290,7 +364,7 @@ async def stream_async( :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/learn/voice-and-video/toll-fraud) 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 @@ -313,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, @@ -334,7 +496,7 @@ def list( :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/learn/voice-and-video/toll-fraud) 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 @@ -344,6 +506,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( iso_code=iso_code, @@ -378,7 +541,7 @@ async def list_async( :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/learn/voice-and-video/toll-fraud) 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 @@ -388,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( @@ -402,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, @@ -423,7 +673,7 @@ def page( :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/learn/voice-and-video/toll-fraud) 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 @@ -435,16 +685,28 @@ def page( "IsoCode": iso_code, "Continent": continent, "CountryCode": country_code, - "LowRiskNumbersEnabled": low_risk_numbers_enabled, - "HighRiskSpecialNumbersEnabled": high_risk_special_numbers_enabled, - "HighRiskTollfraudNumbersEnabled": high_risk_tollfraud_numbers_enabled, + "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, } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CountryPage(self._version, response) async def page_async( @@ -468,7 +730,7 @@ async def page_async( :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/learn/voice-and-video/toll-fraud) 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 @@ -480,20 +742,148 @@ async def page_async( "IsoCode": iso_code, "Continent": continent, "CountryCode": country_code, - "LowRiskNumbersEnabled": low_risk_numbers_enabled, - "HighRiskSpecialNumbersEnabled": high_risk_special_numbers_enabled, - "HighRiskTollfraudNumbersEnabled": high_risk_tollfraud_numbers_enabled, + "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 = await self._version.page_async( - method="GET", uri=self._uri, params=data + method="GET", uri=self._uri, params=data, headers=headers ) 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 ef46284f20..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 @@ -12,9 +12,9 @@ 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 @@ -23,7 +23,6 @@ class HighriskSpecialPrefixInstance(InstanceResource): - """ :ivar prefix: A prefix is a contiguous number range for a block of E.164 numbers that includes the E.164 assigned country code. For example, a North American Numbering Plan prefix like `+1510720` written like `+1(510) 720` matches all numbers inclusive from `+1(510) 720-0000` to `+1(510) 720-9999`. """ @@ -48,12 +47,14 @@ def __repr__(self) -> str: class HighriskSpecialPrefixPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> HighriskSpecialPrefixInstance: """ Build an instance of HighriskSpecialPrefixInstance :param payload: Payload response from the API """ + return HighriskSpecialPrefixInstance( self._version, payload, iso_code=self._solution["iso_code"] ) @@ -68,6 +69,7 @@ def __repr__(self) -> str: class HighriskSpecialPrefixList(ListResource): + def __init__(self, version: Version, iso_code: str): """ Initialize the HighriskSpecialPrefixList @@ -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, @@ -215,8 +319,16 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return HighriskSpecialPrefixPage(self._version, response, self._solution) + 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 HighriskSpecialPrefixPage( + self._version, response, solution=self._solution + ) async def page_async( self, @@ -242,10 +354,90 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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, + } ) - return HighriskSpecialPrefixPage(self._version, response, self._solution) + + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["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: """ @@ -257,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: """ @@ -269,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 5b762c742a..e1787b3ce5 100644 --- a/twilio/rest/voice/v1/dialing_permissions/settings.py +++ b/twilio/rest/voice/v1/dialing_permissions/settings.py @@ -12,9 +12,9 @@ Do not edit the class manually. """ - from typing import Any, Dict, Optional, Union -from twilio.base import values +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 @@ -22,7 +22,6 @@ class SettingsInstance(InstanceResource): - """ :ivar dialing_permissions_inheritance: `true` if the sub-account will inherit voice dialing permissions from the Master Project; otherwise `false`. :ivar url: The absolute URL of this resource. @@ -70,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": @@ -98,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 @@ -109,6 +154,7 @@ def __repr__(self) -> str: class SettingsContext(InstanceContext): + def __init__(self, version: Version): """ Initialize the SettingsContext @@ -119,6 +165,22 @@ def __init__(self, version: Version): self._uri = "/Settings" + 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) -> SettingsInstance: """ Fetch the SettingsInstance @@ -126,16 +188,41 @@ def fetch(self) -> SettingsInstance: :returns: The fetched SettingsInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SettingsInstance( + self._version, + payload, ) - return SettingsInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SettingsInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SettingsInstance: """ @@ -144,16 +231,52 @@ async def fetch_async(self) -> SettingsInstance: :returns: The fetched SettingsInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SettingsInstance( + self._version, + payload, ) - return SettingsInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the SettingsInstance and return response metadata + + + :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( + { + "DialingPermissionsInheritance": serialize.boolean_to_string( + dialing_permissions_inheritance + ), + } + ) + 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, dialing_permissions_inheritance: Union[bool, object] = values.unset @@ -165,19 +288,53 @@ def update( :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( { - "DialingPermissionsInheritance": dialing_permissions_inheritance, + "DialingPermissionsInheritance": serialize.boolean_to_string( + dialing_permissions_inheritance + ), } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SettingsInstance(self._version, payload) + 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, dialing_permissions_inheritance: Union[bool, object] = values.unset @@ -189,19 +346,26 @@ async def update_async( :returns: The updated SettingsInstance """ - data = values.of( - { - "DialingPermissionsInheritance": dialing_permissions_inheritance, - } + payload, _, _ = await self._update_async( + dialing_permissions_inheritance=dialing_permissions_inheritance ) + return SettingsInstance(self._version, payload) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return SettingsInstance(self._version, payload) + :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: """ @@ -214,6 +378,7 @@ def __repr__(self) -> str: class SettingsList(ListResource): + def __init__(self, version: Version): """ Initialize the SettingsList diff --git a/twilio/rest/voice/v1/ip_record.py b/twilio/rest/voice/v1/ip_record.py index c81322d423..9a17301f6d 100644 --- a/twilio/rest/voice/v1/ip_record.py +++ b/twilio/rest/voice/v1/ip_record.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class IpRecordInstance(InstanceResource): - """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the IP Record resource. :ivar sid: The unique string that we created to identify the IP Record resource. @@ -59,6 +58,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[IpRecordContext] = None @property @@ -94,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 @@ -112,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": @@ -140,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 @@ -151,6 +215,7 @@ def __repr__(self) -> str: class IpRecordContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the IpRecordContext @@ -166,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 @@ -173,9 +252,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -185,9 +286,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the IpRecordInstance 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) -> IpRecordInstance: @@ -197,17 +322,43 @@ def fetch(self) -> IpRecordInstance: :returns: The fetched IpRecordInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return IpRecordInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the IpRecordInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> IpRecordInstance: """ @@ -216,17 +367,50 @@ async def fetch_async(self) -> IpRecordInstance: :returns: The fetched IpRecordInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return IpRecordInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return IpRecordInstance( + async def fetch_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine to fetch the IpRecordInstance and return response metadata + + + :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( + { + "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, friendly_name: Union[str, object] = values.unset @@ -238,19 +422,47 @@ def update( :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( { "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + 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 @@ -262,19 +474,24 @@ async def update_async( :returns: The updated IpRecordInstance """ - data = values.of( - { - "FriendlyName": friendly_name, - } - ) + payload, _, _ = await self._update_async(friendly_name=friendly_name) + return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return IpRecordInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -287,12 +504,14 @@ def __repr__(self) -> str: class IpRecordPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> IpRecordInstance: """ Build an instance of IpRecordInstance :param payload: Payload response from the API """ + return IpRecordInstance(self._version, payload) def __repr__(self) -> str: @@ -305,6 +524,7 @@ def __repr__(self) -> str: class IpRecordList(ListResource): + def __init__(self, version: Version): """ Initialize the IpRecordList @@ -316,6 +536,36 @@ def __init__(self, version: Version): self._uri = "/IpRecords" + def _create( + self, + ip_address: str, + friendly_name: Union[str, object] = values.unset, + cidr_prefix_length: Union[int, object] = values.unset, + ) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "IpAddress": ip_address, + "FriendlyName": friendly_name, + "CidrPrefixLength": cidr_prefix_length, + } + ) + 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, ip_address: str, @@ -331,6 +581,49 @@ def create( :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( { "IpAddress": ip_address, @@ -338,14 +631,15 @@ def create( "CidrPrefixLength": cidr_prefix_length, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return IpRecordInstance(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, @@ -362,21 +656,35 @@ async def create_async( :returns: The created IpRecordInstance """ - data = values.of( - { - "IpAddress": ip_address, - "FriendlyName": friendly_name, - "CidrPrefixLength": cidr_prefix_length, - } + payload, _, _ = await self._create_async( + ip_address=ip_address, + friendly_name=friendly_name, + cidr_prefix_length=cidr_prefix_length, ) + return IpRecordInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return IpRecordInstance(self._version, payload) + :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, @@ -428,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, @@ -447,6 +805,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -473,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( @@ -481,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, @@ -505,7 +915,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 IpRecordPage(self._version, response) async def page_async( @@ -532,11 +948,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 b61bee9cc5..d4c30d09f5 100644 --- a/twilio/rest/voice/v1/source_ip_mapping.py +++ b/twilio/rest/voice/v1/source_ip_mapping.py @@ -12,10 +12,10 @@ 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 @@ -24,7 +24,6 @@ class SourceIpMappingInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the IP Record resource. :ivar ip_record_sid: The Twilio-provided string that uniquely identifies the IP Record resource to map from. @@ -53,6 +52,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[SourceIpMappingContext] = None @property @@ -88,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 @@ -106,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 @@ -130,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 @@ -141,6 +201,7 @@ def __repr__(self) -> str: class SourceIpMappingContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SourceIpMappingContext @@ -156,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 @@ -163,9 +238,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -175,9 +272,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SourceIpMappingInstance 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) -> SourceIpMappingInstance: @@ -187,17 +308,43 @@ def fetch(self) -> SourceIpMappingInstance: :returns: The fetched SourceIpMappingInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SourceIpMappingInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SourceIpMappingInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SourceIpMappingInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SourceIpMappingInstance: """ @@ -206,66 +353,130 @@ async def fetch_async(self) -> SourceIpMappingInstance: :returns: The fetched SourceIpMappingInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, - ) - + 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( { "SipDomainSid": sip_domain_sid, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, + headers["Accept"] = "application/json" + + 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( { "SipDomainSid": sip_domain_sid, } ) + headers = values.of({}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, + 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, 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 @@ -277,12 +488,14 @@ def __repr__(self) -> str: class SourceIpMappingPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SourceIpMappingInstance: """ Build an instance of SourceIpMappingInstance :param payload: Payload response from the API """ + return SourceIpMappingInstance(self._version, payload) def __repr__(self) -> str: @@ -295,6 +508,7 @@ def __repr__(self) -> str: class SourceIpMappingList(ListResource): + def __init__(self, version: Version): """ Initialize the SourceIpMappingList @@ -306,6 +520,30 @@ def __init__(self, version: Version): self._uri = "/SourceIpMappings" + def _create(self, ip_record_sid: str, sip_domain_sid: str) -> tuple: + """ + Internal helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "IpRecordSid": ip_record_sid, + "SipDomainSid": sip_domain_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, ip_record_sid: str, sip_domain_sid: str ) -> SourceIpMappingInstance: @@ -317,20 +555,51 @@ def create( :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( { "IpRecordSid": ip_record_sid, "SipDomainSid": sip_domain_sid, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SourceIpMappingInstance(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, ip_record_sid: str, sip_domain_sid: str @@ -343,20 +612,27 @@ async def create_async( :returns: The created SourceIpMappingInstance """ - data = values.of( - { - "IpRecordSid": ip_record_sid, - "SipDomainSid": sip_domain_sid, - } + payload, _, _ = await self._create_async( + ip_record_sid=ip_record_sid, sip_domain_sid=sip_domain_sid ) + return SourceIpMappingInstance(self._version, payload) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return SourceIpMappingInstance(self._version, payload) + :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, @@ -408,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, @@ -427,6 +753,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -453,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( @@ -461,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, @@ -485,7 +863,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SourceIpMappingPage(self._version, response) async def page_async( @@ -512,11 +896,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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/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 "" 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 "".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 "".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 "" diff --git a/twilio/rest/wireless/WirelessBase.py b/twilio/rest/wireless/WirelessBase.py index 5bec36968e..0228c4d666 100644 --- a/twilio/rest/wireless/WirelessBase.py +++ b/twilio/rest/wireless/WirelessBase.py @@ -17,6 +17,7 @@ class WirelessBase(Domain): + def __init__(self, twilio: Client): """ Initialize the Wireless Domain diff --git a/twilio/rest/wireless/v1/__init__.py b/twilio/rest/wireless/v1/__init__.py index 7d94692e45..8f4d0dc5d7 100644 --- a/twilio/rest/wireless/v1/__init__.py +++ b/twilio/rest/wireless/v1/__init__.py @@ -22,6 +22,7 @@ class V1(Version): + def __init__(self, domain: Domain): """ Initialize the V1 version of Wireless diff --git a/twilio/rest/wireless/v1/command.py b/twilio/rest/wireless/v1/command.py index 49c2c74faf..caad0d64b8 100644 --- a/twilio/rest/wireless/v1/command.py +++ b/twilio/rest/wireless/v1/command.py @@ -12,10 +12,10 @@ 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 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 +24,7 @@ class CommandInstance(InstanceResource): + class CommandMode(object): TEXT = "text" BINARY = "binary" @@ -46,7 +47,7 @@ class Transport(object): """ :ivar sid: The unique string that we created to identify the Command resource. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the Command resource. - :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/wireless/api/sim-resource) that the Command was sent to or from. + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Command was sent to or from. :ivar command: The message being sent to or from the SIM. For text mode messages, this can be up to 160 characters. For binary mode messages, this is a series of up to 140 bytes of data encoded using base64. :ivar command_mode: :ivar transport: @@ -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 @@ -151,6 +189,7 @@ def __repr__(self) -> str: class CommandContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the CommandContext @@ -166,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 @@ -173,9 +226,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -185,9 +260,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the CommandInstance 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) -> CommandInstance: @@ -197,17 +296,43 @@ def fetch(self) -> CommandInstance: :returns: The fetched CommandInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CommandInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the CommandInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> CommandInstance: """ @@ -216,17 +341,27 @@ async def fetch_async(self) -> CommandInstance: :returns: The fetched CommandInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return CommandInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return CommandInstance( + 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: """ @@ -239,12 +374,14 @@ def __repr__(self) -> str: class CommandPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> CommandInstance: """ Build an instance of CommandInstance :param payload: Payload response from the API """ + return CommandInstance(self._version, payload) def __repr__(self) -> str: @@ -257,6 +394,7 @@ def __repr__(self) -> str: class CommandList(ListResource): + def __init__(self, version: Version): """ Initialize the CommandList @@ -268,6 +406,46 @@ def __init__(self, version: Version): self._uri = "/Commands" + def _create( + 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 helper for create operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "Command": command, + "Sim": sim, + "CallbackMethod": callback_method, + "CallbackUrl": callback_url, + "CommandMode": command_mode, + "IncludeSid": include_sid, + "DeliveryReceiptRequested": serialize.boolean_to_string( + delivery_receipt_requested + ), + } + ) + 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, command: str, @@ -282,7 +460,7 @@ def create( 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/wireless/api/sim-resource) to send the Command to. + :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: @@ -291,6 +469,69 @@ def create( :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( { "Command": command, @@ -299,17 +540,20 @@ def create( "CallbackUrl": callback_url, "CommandMode": command_mode, "IncludeSid": include_sid, - "DeliveryReceiptRequested": delivery_receipt_requested, + "DeliveryReceiptRequested": serialize.boolean_to_string( + delivery_receipt_requested + ), } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return CommandInstance(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, @@ -325,7 +569,7 @@ async def create_async( 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/wireless/api/sim-resource) to send the Command to. + :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: @@ -334,25 +578,51 @@ async def create_async( :returns: The created CommandInstance """ - data = values.of( - { - "Command": command, - "Sim": sim, - "CallbackMethod": callback_method, - "CallbackUrl": callback_url, - "CommandMode": command_mode, - "IncludeSid": include_sid, - "DeliveryReceiptRequested": delivery_receipt_requested, - } + 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) - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return CommandInstance(self._version, payload) + :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, @@ -369,7 +639,7 @@ def stream( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/wireless/api/sim-resource) to read. + :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`. @@ -408,7 +678,7 @@ async def stream_async( is reached. The results are returned as a generator, so this operation is memory efficient. - :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/wireless/api/sim-resource) to read. + :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`. @@ -432,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, @@ -446,7 +792,7 @@ def list( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/wireless/api/sim-resource) to read. + :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`. @@ -459,6 +805,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( sim=sim, @@ -484,7 +831,7 @@ async def list_async( Unlike stream(), this operation is eager and will load `limit` records into memory before returning. - :param str sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/wireless/api/sim-resource) to read. + :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`. @@ -497,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( @@ -509,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, @@ -523,7 +945,7 @@ def page( Retrieve a single page of CommandInstance records from the API. Request is executed immediately - :param sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/wireless/api/sim-resource) to read. + :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`. @@ -545,7 +967,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 CommandPage(self._version, response) async def page_async( @@ -562,7 +990,7 @@ async def page_async( Asynchronously retrieve a single page of CommandInstance records from the API. Request is executed immediately - :param sim: The `sid` or `unique_name` of the [Sim resources](https://www.twilio.com/docs/wireless/api/sim-resource) to read. + :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`. @@ -584,11 +1012,109 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 2e021e3d8f..77742cf2ba 100644 --- a/twilio/rest/wireless/v1/rate_plan.py +++ b/twilio/rest/wireless/v1/rate_plan.py @@ -12,10 +12,10 @@ 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 @@ -25,17 +25,21 @@ 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. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the RatePlan resource. :ivar friendly_name: The string that you assigned to describe the resource. :ivar data_enabled: Whether SIMs can use GPRS/3G/4G/LTE data connectivity. - :ivar 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/wireless/api/rateplan-resource#payg-vs-quota-data-plans). + :ivar 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). :ivar 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. - :ivar messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/wireless/api/command-resource). + :ivar messaging_enabled: Whether SIMs can make, send, and receive SMS using [Commands](https://www.twilio.com/docs/iot/wireless/api/command-resource). :ivar voice_enabled: Deprecated. Whether SIMs can make and receive voice calls. - :ivar 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/wireless/api/rateplan-resource#national-roaming). + :ivar 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). :ivar 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. :ivar 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`. :ivar 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. @@ -81,6 +85,7 @@ def __init__( self._solution = { "sid": sid or self.sid, } + self._context: Optional[RatePlanContext] = None @property @@ -116,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 @@ -134,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, @@ -170,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 @@ -181,6 +258,7 @@ def __repr__(self) -> str: class RatePlanContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the RatePlanContext @@ -196,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 @@ -203,9 +295,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -215,9 +329,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the RatePlanInstance 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) -> RatePlanInstance: @@ -227,17 +365,43 @@ def fetch(self) -> RatePlanInstance: :returns: The fetched RatePlanInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RatePlanInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the RatePlanInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> RatePlanInstance: """ @@ -246,17 +410,55 @@ async def fetch_async(self) -> RatePlanInstance: :returns: The fetched RatePlanInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return RatePlanInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return RatePlanInstance( + 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, + ) -> tuple: + """ + Internal helper for update operation + + Returns: + tuple: (payload, status_code, headers) + """ + + data = values.of( + { + "UniqueName": unique_name, + "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, @@ -271,20 +473,57 @@ def update( :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( { "UniqueName": unique_name, "FriendlyName": friendly_name, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + 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, @@ -299,20 +538,29 @@ async def update_async( :returns: The updated RatePlanInstance """ - data = values.of( - { - "UniqueName": unique_name, - "FriendlyName": friendly_name, - } + payload, _, _ = await self._update_async( + unique_name=unique_name, friendly_name=friendly_name ) + return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) + 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 - return RatePlanInstance(self._version, payload, sid=self._solution["sid"]) + :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: """ @@ -325,12 +573,14 @@ def __repr__(self) -> str: class RatePlanPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> RatePlanInstance: """ Build an instance of RatePlanInstance :param payload: Payload response from the API """ + return RatePlanInstance(self._version, payload) def __repr__(self) -> str: @@ -343,6 +593,7 @@ def __repr__(self) -> str: class RatePlanList(ListResource): + def __init__(self, version: Version): """ Initialize the RatePlanList @@ -354,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, @@ -367,51 +618,48 @@ 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/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/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/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/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( { "UniqueName": unique_name, "FriendlyName": friendly_name, - "DataEnabled": data_enabled, + "DataEnabled": serialize.boolean_to_string(data_enabled), "DataLimit": data_limit, "DataMetering": data_metering, - "MessagingEnabled": messaging_enabled, - "VoiceEnabled": voice_enabled, - "NationalRoamingEnabled": national_roaming_enabled, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), "InternationalRoaming": serialize.map( international_roaming, lambda e: e ), "NationalRoamingDataLimit": national_roaming_data_limit, "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) - payload = self._version.create( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return RatePlanInstance(self._version, payload) + headers["Accept"] = "application/json" - async def create_async( + 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, friendly_name: Union[str, object] = values.unset, @@ -424,50 +672,253 @@ 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. :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/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/wireless/api/command-resource). + :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/wireless/api/rateplan-resource#national-roaming). + :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/wireless/api/rateplan-resource#national-roaming) for more info. + :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( { "UniqueName": unique_name, "FriendlyName": friendly_name, - "DataEnabled": data_enabled, + "DataEnabled": serialize.boolean_to_string(data_enabled), "DataLimit": data_limit, "DataMetering": data_metering, - "MessagingEnabled": messaging_enabled, - "VoiceEnabled": voice_enabled, - "NationalRoamingEnabled": national_roaming_enabled, + "MessagingEnabled": serialize.boolean_to_string(messaging_enabled), + "VoiceEnabled": serialize.boolean_to_string(voice_enabled), + "NationalRoamingEnabled": serialize.boolean_to_string( + national_roaming_enabled + ), "InternationalRoaming": serialize.map( international_roaming, lambda e: e ), "NationalRoamingDataLimit": national_roaming_data_limit, "InternationalRoamingDataLimit": international_roaming_data_limit, + "DataLimitStrategy": data_limit_strategy, } ) + headers = values.of({"Content-Type": "application/x-www-form-urlencoded"}) + + headers["Content-Type"] = "application/x-www-form-urlencoded" - payload = await self._version.create_async( - method="POST", - uri=self._uri, - data=data, + 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, + 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, @@ -518,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, @@ -537,6 +1038,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( limit=limit, @@ -563,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( @@ -571,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, @@ -595,7 +1148,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 RatePlanPage(self._version, response) async def page_async( @@ -622,11 +1181,85 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 19387ee99e..33fee1d428 100644 --- a/twilio/rest/wireless/v1/sim/__init__.py +++ b/twilio/rest/wireless/v1/sim/__init__.py @@ -12,10 +12,10 @@ 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 @@ -26,6 +26,7 @@ class SimInstance(InstanceResource): + class ResetStatus(object): RESETTING = "resetting" @@ -43,13 +44,13 @@ class Status(object): :ivar sid: The unique string that we created to identify the Sim 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. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) to which the Sim resource belongs. - :ivar rate_plan_sid: The SID of the [RatePlan resource](https://www.twilio.com/docs/wireless/api/rateplan-resource) to which the Sim resource is assigned. + :ivar rate_plan_sid: The SID of the [RatePlan resource](https://www.twilio.com/docs/iot/wireless/api/rateplan-resource) to which the Sim resource is assigned. :ivar friendly_name: The string that you assigned to describe the Sim resource. :ivar iccid: The [ICCID](https://en.wikipedia.org/wiki/SIM_card#ICCID) associated with the SIM. :ivar e_id: Deprecated. :ivar status: :ivar reset_status: - :ivar commands_callback_url: The URL we call using the `commands_callback_method` when the SIM originates a machine-to-machine [Command](https://www.twilio.com/docs/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body will be ignored. + :ivar commands_callback_url: The URL we call using the `commands_callback_method` when the SIM originates a machine-to-machine [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 will be ignored. :ivar commands_callback_method: The HTTP method we use to call `commands_callback_url`. Can be: `POST` or `GET`. Default is `POST`. :ivar sms_fallback_method: Deprecated. :ivar sms_fallback_url: Deprecated. @@ -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, @@ -188,20 +226,20 @@ def update( :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/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :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/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :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/wireless/api/command-resource). + :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/wireless/api/sim-resource#move-sims-between-subaccounts). + :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 """ @@ -254,20 +292,20 @@ async def update_async( :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/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :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/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :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/wireless/api/command-resource). + :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/wireless/api/sim-resource#move-sims-between-subaccounts). + :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 """ @@ -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: """ @@ -317,6 +487,7 @@ def __repr__(self) -> str: class SimContext(InstanceContext): + def __init__(self, version: Version, sid: str): """ Initialize the SimContext @@ -335,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 @@ -342,9 +527,31 @@ def delete(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return self._version.delete( - method="DELETE", - uri=self._uri, + 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 await self._version.delete_with_response_info_async( + method="DELETE", uri=self._uri, headers=headers ) async def delete_async(self) -> bool: @@ -354,9 +561,33 @@ async def delete_async(self) -> bool: :returns: True if delete succeeds, False otherwise """ - return await self._version.delete_async( - method="DELETE", - uri=self._uri, + success, _, _ = await self._delete_async() + return success + + async def delete_with_http_info_async(self) -> ApiResponse: + """ + Asynchronous coroutine that deletes the SimInstance 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) -> SimInstance: @@ -366,17 +597,43 @@ def fetch(self) -> SimInstance: :returns: The fetched SimInstance """ - - payload = self._version.fetch( - method="GET", - uri=self._uri, + payload, _, _ = self._fetch() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SimInstance( + def fetch_with_http_info(self) -> ApiResponse: + """ + Fetch the SimInstance and return response metadata + + + :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" + + return await self._version.fetch_with_response_info_async( + method="GET", uri=self._uri, headers=headers + ) async def fetch_async(self) -> SimInstance: """ @@ -385,19 +642,29 @@ async def fetch_async(self) -> SimInstance: :returns: The fetched SimInstance """ - - payload = await self._version.fetch_async( - method="GET", - uri=self._uri, + payload, _, _ = await self._fetch_async() + return SimInstance( + self._version, + payload, + sid=self._solution["sid"], ) - return SimInstance( + 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( + def _update( self, unique_name: Union[str, object] = values.unset, callback_method: Union[str, object] = values.unset, @@ -417,31 +684,14 @@ 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/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/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/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/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( { "UniqueName": unique_name, @@ -464,16 +714,17 @@ def update( "AccountSid": account_sid, } ) + headers = values.of({}) - payload = self._version.update( - method="POST", - uri=self._uri, - data=data, - ) + headers["Content-Type"] = "application/x-www-form-urlencoded" - return SimInstance(self._version, payload, sid=self._solution["sid"]) + headers["Accept"] = "application/json" - async def update_async( + 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, callback_method: Union[str, object] = values.unset, @@ -495,65 +746,319 @@ 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`. :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/wireless/api/rateplan-resource) to which the Sim resource should be assigned. + :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/wireless/api/command-resource). Your server should respond with an HTTP status code in the 200 range; any response body is ignored. + :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/wireless/api/command-resource). + :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/wireless/api/sim-resource#move-sims-between-subaccounts). + :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 """ - 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, - "ResetStatus": reset_status, - "AccountSid": account_sid, - } - ) - - payload = await self._version.update_async( - method="POST", - uri=self._uri, - data=data, - ) - - return SimInstance(self._version, payload, sid=self._solution["sid"]) - - @property - def data_sessions(self) -> DataSessionList: - """ - Access the data_sessions - """ + 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( + { + "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, + "ResetStatus": reset_status, + "AccountSid": account_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, + 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: + """ + Access the data_sessions + """ if self._data_sessions is None: self._data_sessions = DataSessionList( self._version, @@ -584,12 +1089,14 @@ def __repr__(self) -> str: class SimPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> SimInstance: """ Build an instance of SimInstance :param payload: Payload response from the API """ + return SimInstance(self._version, payload) def __repr__(self) -> str: @@ -602,6 +1109,7 @@ def __repr__(self) -> str: class SimList(ListResource): + def __init__(self, version: Version): """ Initialize the SimList @@ -631,7 +1139,7 @@ def stream( :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/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :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() @@ -673,7 +1181,7 @@ async def stream_async( :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/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :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() @@ -697,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, @@ -714,7 +1304,7 @@ def list( :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/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :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 @@ -726,6 +1316,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( status=status, @@ -755,7 +1346,7 @@ async def list_async( :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/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :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 @@ -767,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( @@ -780,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, @@ -797,7 +1469,7 @@ def page( :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/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :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 @@ -819,7 +1491,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 SimPage(self._version, response) async def page_async( @@ -839,7 +1517,7 @@ async def page_async( :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/wireless/api/rateplan-resource). Only return Sim resources assigned to this RatePlan resource. + :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 @@ -861,11 +1539,115 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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 6a9a576749..cb0c14dc69 100644 --- a/twilio/rest/wireless/v1/sim/data_session.py +++ b/twilio/rest/wireless/v1/sim/data_session.py @@ -12,10 +12,10 @@ 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_resource import InstanceResource from twilio.base.list_resource import ListResource @@ -24,18 +24,17 @@ class DataSessionInstance(InstanceResource): - """ :ivar sid: The unique string that we created to identify the DataSession resource. - :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/wireless/api/sim-resource) that the Data Session is for. + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that the Data Session is for. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the DataSession resource. :ivar radio_link: The generation of wireless technology that the device was using. :ivar operator_mcc: The 'mobile country code' is the unique ID of the home country where the Data Session took place. See: [MCC/MNC lookup](http://mcc-mnc.com/). :ivar operator_mnc: The 'mobile network code' is the unique ID specific to the mobile operator network where the Data Session took place. :ivar operator_country: The three letter country code representing where the device's Data Session took place. This is determined by looking up the `operator_mcc`. - :ivar operator_name: The friendly name of the mobile operator network that the [SIM](https://www.twilio.com/docs/wireless/api/sim-resource)-connected device is attached to. This is determined by looking up the `operator_mnc`. + :ivar operator_name: The friendly name of the mobile operator network that the [SIM](https://www.twilio.com/docs/iot/wireless/api/sim-resource)-connected device is attached to. This is determined by looking up the `operator_mnc`. :ivar cell_id: The unique ID of the cellular tower that the device was attached to at the moment when the Data Session was last updated. - :ivar cell_location_estimate: An object that describes the estimated location in latitude and longitude where the device's Data Session took place. The location is derived from the `cell_id` when the Data Session was last updated. See [Cell Location Estimate Object](https://www.twilio.com/docs/wireless/api/datasession-resource#cell-location-estimate-object). + :ivar cell_location_estimate: An object that describes the estimated location in latitude and longitude where the device's Data Session took place. The location is derived from the `cell_id` when the Data Session was last updated. See [Cell Location Estimate Object](https://www.twilio.com/docs/iot/wireless/api/datasession-resource#cell-location-estimate-object). :ivar packets_uploaded: The number of packets uploaded by the device between the `start` time and when the Data Session was last updated. :ivar packets_downloaded: The number of packets downloaded by the device between the `start` time and when the Data Session was last updated. :ivar last_updated: The date that the resource was last updated, given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. @@ -89,12 +88,14 @@ def __repr__(self) -> str: class DataSessionPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> DataSessionInstance: """ Build an instance of DataSessionInstance :param payload: Payload response from the API """ + return DataSessionInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -109,12 +110,13 @@ def __repr__(self) -> str: class DataSessionList(ListResource): + def __init__(self, version: Version, sim_sid: str): """ Initialize the DataSessionList :param version: Version that contains the resource - :param sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/wireless/api/sim-resource) with the Data Sessions to read. + :param sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) with the Data Sessions to read. """ super().__init__(version) @@ -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, @@ -252,8 +356,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return DataSessionPage(self._version, response, self._solution) + 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 DataSessionPage(self._version, response, solution=self._solution) async def page_async( self, @@ -279,10 +389,84 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return DataSessionPage(self._version, response, self._solution) + 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: """ @@ -294,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: """ @@ -306,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 2ee25ded7b..5b1c6b2512 100644 --- a/twilio/rest/wireless/v1/sim/usage_record.py +++ b/twilio/rest/wireless/v1/sim/usage_record.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,17 +24,18 @@ class UsageRecordInstance(InstanceResource): + class Granularity(object): HOURLY = "hourly" DAILY = "daily" ALL = "all" """ - :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/wireless/api/sim-resource) that this Usage Record is for. + :ivar sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) that this Usage Record is for. :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the UsageRecord resource. :ivar period: The time period for which the usage is reported. Contains `start` and `end` datetime values given as GMT in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. - :ivar commands: An object that describes the SIM's usage of Commands during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/wireless/api/sim-usagerecord-resource#commands-usage-object). - :ivar data: An object that describes the SIM's data usage during the specified period. See [Data Usage Object](https://www.twilio.com/docs/wireless/api/sim-usagerecord-resource#data-usage-object). + :ivar commands: An object that describes the SIM's usage of Commands during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#commands-usage-object). + :ivar data: An object that describes the SIM's data usage during the specified period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/sim-usagerecord-resource#data-usage-object). """ def __init__(self, version: Version, payload: Dict[str, Any], sim_sid: str): @@ -61,12 +62,14 @@ def __repr__(self) -> str: class UsageRecordPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: """ Build an instance of UsageRecordInstance :param payload: Payload response from the API """ + return UsageRecordInstance( self._version, payload, sim_sid=self._solution["sim_sid"] ) @@ -81,12 +84,13 @@ def __repr__(self) -> str: class UsageRecordList(ListResource): + def __init__(self, version: Version, sim_sid: str): """ Initialize the UsageRecordList :param version: Version that contains the resource - :param sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/wireless/api/sim-resource) to read the usage from. + :param sim_sid: The SID of the [Sim resource](https://www.twilio.com/docs/iot/wireless/api/sim-resource) to read the usage from. """ super().__init__(version) @@ -163,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, @@ -188,6 +256,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end=end, @@ -223,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( @@ -234,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, @@ -267,8 +405,14 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) - return UsageRecordPage(self._version, response, self._solution) + 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 UsageRecordPage(self._version, response, solution=self._solution) async def page_async( self, @@ -303,10 +447,102 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers + ) + 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 + ) ) - return UsageRecordPage(self._version, response, self._solution) + 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: """ @@ -318,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: """ @@ -330,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 18f25ae59b..034ab18ab2 100644 --- a/twilio/rest/wireless/v1/usage_record.py +++ b/twilio/rest/wireless/v1/usage_record.py @@ -12,10 +12,10 @@ Do not edit the class manually. """ - 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 @@ -24,6 +24,7 @@ class UsageRecordInstance(InstanceResource): + class Granularity(object): HOURLY = "hourly" DAILY = "daily" @@ -32,8 +33,8 @@ class Granularity(object): """ :ivar account_sid: The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the AccountUsageRecord resource. :ivar period: The time period for which usage is reported. Contains `start` and `end` properties that describe the period using GMT date-time values specified in [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format. - :ivar commands: An object that describes the aggregated Commands usage for all SIMs during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/wireless/api/account-usagerecord-resource#commands-usage-object). - :ivar data: An object that describes the aggregated Data usage for all SIMs over the period. See [Data Usage Object](https://www.twilio.com/docs/wireless/api/account-usagerecord-resource#data-usage-object). + :ivar commands: An object that describes the aggregated Commands usage for all SIMs during the specified period. See [Commands Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#commands-usage-object). + :ivar data: An object that describes the aggregated Data usage for all SIMs over the period. See [Data Usage Object](https://www.twilio.com/docs/iot/wireless/api/account-usagerecord-resource#data-usage-object). """ def __init__(self, version: Version, payload: Dict[str, Any]): @@ -55,12 +56,14 @@ def __repr__(self) -> str: class UsageRecordPage(Page): + def get_instance(self, payload: Dict[str, Any]) -> UsageRecordInstance: """ Build an instance of UsageRecordInstance :param payload: Payload response from the API """ + return UsageRecordInstance(self._version, payload) def __repr__(self) -> str: @@ -73,6 +76,7 @@ def __repr__(self) -> str: class UsageRecordList(ListResource): + def __init__(self, version: Version): """ Initialize the UsageRecordList @@ -150,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, @@ -175,6 +243,7 @@ def list( :returns: list that will contain up to limit results """ + return list( self.stream( end=end, @@ -210,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( @@ -221,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, @@ -254,7 +392,13 @@ def page( } ) - response = self._version.page(method="GET", uri=self._uri, params=data) + 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 UsageRecordPage(self._version, response) async def page_async( @@ -290,11 +434,103 @@ async def page_async( } ) + 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 + method="GET", uri=self._uri, params=data, headers=headers ) 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/messaging_response.py b/twilio/twiml/messaging_response.py index b938e16448..ec36c74c06 100644 --- a/twilio/twiml/messaging_response.py +++ b/twilio/twiml/messaging_response.py @@ -34,7 +34,7 @@ def message( :param body: Message Body :param to: Phone Number to send Message to :param from: Phone Number to send Message from - :param action: Action URL + :param action: A URL specifying where Twilio should send status callbacks for the created outbound message. :param method: Action URL Method :param status_callback: Status callback URL. Deprecated in favor of action. :param kwargs: additional attributes diff --git a/twilio/twiml/voice_response.py b/twilio/twiml/voice_response.py index 7fb59a4a83..384c492778 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, @@ -50,6 +51,7 @@ def dial( sequential=None, refer_url=None, refer_method=None, + events=None, **kwargs ): """ @@ -65,6 +67,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 @@ -73,6 +76,7 @@ def dial( :param sequential: Used to determine if child TwiML nouns should be dialed in order, one after the other (sequential) or dial all at once (parallel). Default is false, parallel :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 kwargs: additional attributes :returns: element @@ -89,6 +93,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, @@ -97,6 +102,7 @@ def dial( sequential=sequential, refer_url=refer_url, refer_method=refer_method, + events=events, **kwargs ) ) @@ -310,6 +316,7 @@ def record( recording_status_callback_event=None, transcribe=None, transcribe_callback=None, + recording_configuration_id=None, **kwargs ): """ @@ -327,6 +334,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: element @@ -345,6 +353,7 @@ def record( recording_status_callback_event=recording_status_callback_event, transcribe=transcribe, transcribe_callback=transcribe_callback, + recording_configuration_id=recording_configuration_id, **kwargs ) ) @@ -631,28 +640,116 @@ def stream( ) ) - def siprec(self, name=None, connector_name=None, track=None, **kwargs): + def siprec( + self, + name=None, + connector_name=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): """ Create a element :param name: Friendly name given to SIPREC :param connector_name: Unique name for Connector :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method :param kwargs: additional attributes :returns: element """ return self.nest( - Siprec(name=name, connector_name=connector_name, track=track, **kwargs) + Siprec( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def transcription( + self, + name=None, + track=None, + status_callback_url=None, + status_callback_method=None, + inbound_track_label=None, + outbound_track_label=None, + partial_results=None, + language_code=None, + transcription_engine=None, + profanity_filter=None, + speech_model=None, + hints=None, + enable_automatic_punctuation=None, + intelligence_service=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name given to the Transcription + :param track: Track to be analyze by the provider + :param status_callback_url: Status Callback URL + :param status_callback_method: Status Callback URL method + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track Label + :param partial_results: Indicates if partial results are going to be send to the customer + :param language_code: Language Code used by the transcription engine + :param transcription_engine: Transcription Engine to be used + :param profanity_filter: Enable Profanity Filter + :param speech_model: Speech Model used by the transcription engine + :param hints: Hints to be provided to the transcription engine + :param enable_automatic_punctuation: Enable Automatic Punctuation + :param intelligence_service: The SID or the unique name of the Intelligence Service to be used + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Transcription( + 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, + **kwargs + ) ) -class Siprec(TwiML): - """ TwiML Noun""" +class Transcription(TwiML): + """ TwiML Noun""" def __init__(self, **kwargs): - super(Siprec, self).__init__(**kwargs) - self.name = "Siprec" + super(Transcription, self).__init__(**kwargs) + self.name = "Transcription" + + def config(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom config + :param value: The value of the custom config + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Config(name=name, value=value, **kwargs)) def parameter(self, name=None, value=None, **kwargs): """ @@ -675,6 +772,34 @@ def __init__(self, **kwargs): self.name = "Parameter" +class Config(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Config, self).__init__(**kwargs) + self.name = "Config" + + +class Siprec(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Siprec, self).__init__(**kwargs) + self.name = "Siprec" + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + class Stream(TwiML): """ TwiML Noun""" @@ -737,21 +862,143 @@ def stream( ) ) - def siprec(self, name=None, connector_name=None, track=None, **kwargs): + def siprec( + self, + name=None, + connector_name=None, + track=None, + status_callback=None, + status_callback_method=None, + **kwargs + ): """ Create a element :param name: Friendly name given to SIPREC :param connector_name: Unique name for Connector :param track: Track to be streamed to remote service + :param status_callback: Status Callback URL + :param status_callback_method: Status Callback URL method :param kwargs: additional attributes :returns: element """ return self.nest( - Siprec(name=name, connector_name=connector_name, track=track, **kwargs) + Siprec( + name=name, + connector_name=connector_name, + track=track, + status_callback=status_callback, + status_callback_method=status_callback_method, + **kwargs + ) + ) + + def transcription( + self, + name=None, + track=None, + status_callback_url=None, + status_callback_method=None, + inbound_track_label=None, + outbound_track_label=None, + partial_results=None, + language_code=None, + transcription_engine=None, + profanity_filter=None, + speech_model=None, + hints=None, + enable_automatic_punctuation=None, + intelligence_service=None, + **kwargs + ): + """ + Create a element + + :param name: Friendly name given to the Transcription + :param track: Track to be analyze by the provider + :param status_callback_url: Status Callback URL + :param status_callback_method: Status Callback URL method + :param inbound_track_label: Friendly name given to the Inbound Track + :param outbound_track_label: Friendly name given to the Outbound Track Label + :param partial_results: Indicates if partial results are going to be send to the customer + :param language_code: Language Code used by the transcription engine + :param transcription_engine: Transcription Engine to be used + :param profanity_filter: Enable Profanity Filter + :param speech_model: Speech Model used by the transcription engine + :param hints: Hints to be provided to the transcription engine + :param enable_automatic_punctuation: Enable Automatic Punctuation + :param intelligence_service: The SID or the unique name of the Intelligence Service to be used + :param kwargs: additional attributes + + :returns: element + """ + return self.nest( + Transcription( + 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, + **kwargs + ) ) + 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 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: 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): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Recording, self).__init__(**kwargs) + self.name = "Recording" + class Prompt(TwiML): """ Twiml Verb""" @@ -1983,6 +2230,7 @@ def conference( wait_method=None, max_participants=None, record=None, + recording_configuration_id=None, region=None, coach=None, trim=None, @@ -2009,6 +2257,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 @@ -2036,6 +2285,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, @@ -2159,7 +2409,7 @@ def sim(self, sim_sid, **kwargs): def sip( self, - sip_url, + sip_url=None, username=None, password=None, url=None, @@ -2200,7 +2450,7 @@ def sip( """ return self.nest( Sip( - sip_url, + sip_url=sip_url, username=username, password=password, url=url, @@ -2260,6 +2510,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 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: 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): + """ TwiML Noun""" + + def __init__(self, phone_number, **kwargs): + super(WhatsApp, self).__init__(**kwargs) + self.name = "WhatsApp" + self.value = phone_number + class Application(TwiML): """ TwiML Noun""" @@ -2306,10 +2600,93 @@ def __init__(self, sid, **kwargs): class Sip(TwiML): """ 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 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: element + """ + return self.nest( + SipUri( + sip_url=sip_url, + priority=priority, + weight=weight, + username=username, + password=password, + **kwargs + ) + ) + + def headers(self, **kwargs): + """ + Create a element + + :param kwargs: additional attributes + + :returns: 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
element + + :param name: The name of the custom header + :param value: The value of the custom header + :param kwargs: additional attributes + + :returns:
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): @@ -2539,6 +2916,347 @@ def conversation( ) ) + def conversation_relay( + self, + url=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, + 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 + ): + """ + Create a element + + :param url: URL of the remote service where the session is connected to + :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 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: element + """ + return self.nest( + ConversationRelay( + url=url, + 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, + 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, + 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, + **kwargs + ): + """ + Create a 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 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 kwargs: additional attributes + + :returns: 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, + 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, + **kwargs + ) + ) + + def ai_session(self, ai_connector=None, ai_session_configuration=None, **kwargs): + """ + Create a element + + :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: element + """ + return self.nest( + AiSession( + ai_connector=ai_connector, + ai_session_configuration=ai_session_configuration, + **kwargs + ) + ) + + def conversation_relay_session( + self, connector=None, session_configuration=None, **kwargs + ): + """ + Create a element + + :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: element + """ + return self.nest( + ConversationRelaySession( + connector=connector, + session_configuration=session_configuration, + **kwargs + ) + ) + + +class ConversationRelaySession(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(ConversationRelaySession, self).__init__(**kwargs) + self.name = "ConversationRelaySession" + + +class AiSession(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(AiSession, self).__init__(**kwargs) + self.name = "AiSession" + + +class Assistant(TwiML): + """ 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 + ): + """ + Create a 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 kwargs: additional attributes + + :returns: element + """ + return self.nest( + Language( + code=code, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + **kwargs + ) + ) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + + +class Language(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(Language, self).__init__(**kwargs) + self.name = "Language" + + +class ConversationRelay(TwiML): + """ TwiML Noun""" + + def __init__(self, **kwargs): + super(ConversationRelay, self).__init__(**kwargs) + self.name = "ConversationRelay" + + def language( + self, + code=None, + tts_provider=None, + voice=None, + transcription_provider=None, + speech_model=None, + **kwargs + ): + """ + Create a 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 kwargs: additional attributes + + :returns: element + """ + return self.nest( + Language( + code=code, + tts_provider=tts_provider, + voice=voice, + transcription_provider=transcription_provider, + speech_model=speech_model, + **kwargs + ) + ) + + def parameter(self, name=None, value=None, **kwargs): + """ + Create a element + + :param name: The name of the custom parameter + :param value: The value of the custom parameter + :param kwargs: additional attributes + + :returns: element + """ + return self.nest(Parameter(name=name, value=value, **kwargs)) + class Conversation(TwiML): """ TwiML Noun""" @@ -2580,14 +3298,6 @@ def parameter(self, name=None, value=None, **kwargs): return self.nest(Parameter(name=name, value=value, **kwargs)) -class Config(TwiML): - """ TwiML Noun""" - - def __init__(self, **kwargs): - super(Config, self).__init__(**kwargs) - self.name = "Config" - - class Autopilot(TwiML): """ TwiML Noun"""